Is there a portable way to get the current username in Python?

前端 未结 12 819
别那么骄傲
别那么骄傲 2020-11-22 03:11

Is there a portable way to get the current user\'s username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid

12条回答
  •  别那么骄傲
    2020-11-22 03:58

    You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess → OpenProcessToken → GetTokenInformation → LookupAccountSid).

    I wrote a small module that can do this straight from Python, getuser.py. Usage:

    import getuser
    print(getuser.lookup_username())
    

    It works on both Windows and *nix (the latter uses the pwd module as described in the other answers).

提交回复
热议问题