Is there a portable way to get the current username in Python?
Is there a portable way to get the current user's username in Python (ie, one that works under both Linux and Windows, at least). It would work like os.getuid
:
>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (eg, running as a Windows service), although I haven't verified that.
Look at getpass module
import getpass
getpass.getuser()
'kostya'
Availability: Unix, Windows
ps 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)."
You best bet would be to combine os.getuid()
with pwd.getpwuid()
:
import os
import pwd
def get_username():
return pwd.getpwuid( os.getuid() )[ 0 ]
Refer to the pwd docs for more details:
http://docs.python.org/library/pwd.html
你也可以使用:
os.getlogin()
链接地址: http://www.djcxy.com/p/2242.html