patternpythonCriticalCanonical
Is there a portable way to get the current username in Python?
Viewed 0 times
usernameportablethecurrentwaygetpythonthere
Problem
What is a portable way (e.g. for Linux and Windows) to get the current user's username? Something similar to
The
os.getuid() would be nice:>>> os.getuid()
42
# Does not currently exist in Python
>>> os.getusername()
'slartibartfast'The
pwd module works for Unix only. Some people suggest that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service).Solution
Look at
Availability: Unix, Windows
p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."
getpass moduleimport getpass
getpass.getuser()
'kostya'Availability: Unix, Windows
p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."
Code Snippets
import getpass
getpass.getuser()
'kostya'Context
Stack Overflow Q#842059, score: 1123
Revisions (0)
No revisions yet.