问题:有没有一种可移植的方法来获取Python中的当前用户名?
有没有一种可移植的方式来获取Python中当前用户的用户名(即,至少在Linux和Windows下都可以使用的用户名)。它会像这样工作os.getuid
:
>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
我四处搜寻,很惊讶地没有找到一个明确的答案(尽管也许我只是在谷歌搜索方面很差)。该PWD模块提供了一个相对简单的方法来实现这一目标下,说,Linux的,但它不存在于Windows。一些搜索结果表明,在某些情况下(例如,作为Windows服务运行),在Windows下获取用户名可能会很复杂,尽管我尚未对此进行验证。
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
:
>>> 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 (e.g., running as a Windows service), although I haven’t verified that.
回答 0
看一下getpass模块
import getpass
getpass.getuser()
'kostya'
可用性:Unix,Windows
ps在下面的每个注释中:“ 此函数查看各种环境变量的值以确定用户名。因此,不应出于访问控制目的(或可能出于任何其他目的)依赖此函数,因为它允许任何用户模仿任何其他用户)。 “
Look at getpass module
import 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).“
回答 1
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
回答 2
You can also use:
os.getlogin()
回答 3
您可能可以使用:
os.environ.get('USERNAME')
要么
os.environ.get('USER')
但这不是安全的,因为可以更改环境变量。
You can probably use:
os.environ.get('USERNAME')
or
os.environ.get('USER')
But it’s not going to be safe because environment variables can be changed.
回答 4
回答 5
如果您需要此文件来获取用户的主目录,则可以将以下内容视为可移植的(至少是win32和linux),是标准库的一部分。
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
您也可以解析这样的字符串以仅获取最后的路径组件(即用户名)。
参见:os.path.expanduser
If you are needing this to get user’s home dir, below could be considered as portable (win32 and linux at least), part of a standard library.
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
Also you could parse such string to get only last path component (ie. user name).
See: os.path.expanduser
回答 6
对我来说,使用os
模块看起来最适合可移植性:在Linux和Windows上均能最佳工作。
import os
# Gives user's home directory
userhome = os.path.expanduser('~')
print "User's home Dir: " + userhome
# Gives username by splitting path based on OS
print "username: " + os.path.split(userhome)[-1]
输出:
视窗:
用户的主目录:C:\ Users \ myuser
用户名:myuser
Linux:
用户的主目录:/ root
用户名:root
无需安装任何模块或扩展。
To me using os
module looks the best for portability: Works best on both Linux and Windows.
import os
# Gives user's home directory
userhome = os.path.expanduser('~')
print "User's home Dir: " + userhome
# Gives username by splitting path based on OS
print "username: " + os.path.split(userhome)[-1]
Output:
Windows:
User’s home Dir: C:\Users\myuser
username: myuser
Linux:
User’s home Dir: /root
username: root
No need of installing any modules or extensions.
回答 7
结合pwd
和getpass
方法,基于其他答案:
try:
import pwd
except ImportError:
import getpass
pwd = None
def current_user():
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
Combined pwd
and getpass
approach, based on other answers:
try:
import pwd
except ImportError:
import getpass
pwd = None
def current_user():
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
回答 8
至少对于UNIX,这是有效的…
import commands
username = commands.getoutput("echo $(whoami)")
print username
编辑:
我只是查了一下,这适用于Windows和UNIX:
import commands
username = commands.getoutput("whoami")
在UNIX上,它将返回您的用户名,但在Windows上,它将返回用户的组,斜线和用户名。
–
IE浏览器
UNIX返回:“用户名”
Windows返回:“域/用户名”
–
这很有趣,但可能并不理想,除非您无论如何都要在终端上做一些事情……在这种情况下,您可能会os.system
开始使用它。例如,前一阵子我需要将用户添加到组中,所以我做到了(请注意,这是在Linux中)
import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"
我觉得这更容易阅读,您不必导入pwd或getpass。
我也觉得在Windows中的某些应用程序中使用“域/用户”可能会有所帮助。
For UNIX, at least, this works…
import commands
username = commands.getoutput("echo $(whoami)")
print username
edit:
I just looked it up and this works on Windows and UNIX:
import commands
username = commands.getoutput("whoami")
On UNIX it returns your username, but on Windows, it returns your user’s group, slash, your username.
—
I.E.
UNIX returns: “username”
Windows returns: “domain/username”
—
It’s interesting, but probably not ideal unless you are doing something in the the terminal anyway… in which case you would probably be using os.system
to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)
import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"
I feel like that is easier to read and you don’t have to import pwd or getpass.
I also feel like having “domain/user” could be helpful in certain applications in Windows.
回答 9
I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things):
http://www.decalage.info/en/python/plx
Usage:
import plx
username = plx.get_username()
(it requires win32 extensions on Windows)
回答 10
仅使用标准python库:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
适用于Windows,Mac或Linux
或者,您可以通过立即调用删除一行:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
Using only standard python libs:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
Works on Windows, Mac or Linux
Alternatively, you could remove one line with an immediate invocation:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
回答 11
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).