有没有一种可移植的方法来获取Python中的当前用户名?

问题:有没有一种可移植的方法来获取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

您最好的选择是与结合os.getuid()使用pwd.getpwuid()

import os
import pwd

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]

有关更多详细信息,请参阅pwd文档:

http://docs.python.org/library/pwd.html

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

您还可以使用:

 os.getlogin()

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

这些可能有效。我不知道它们作为服务运行时的行为。他们是不可移植的,但是这就是os.nameif语句是。

win32api.GetUserName()

win32api.GetUserNameEx(...) 

参见:http : //timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html

These might work. I don’t know how they behave when running as a service. They aren’t portable, but that’s what os.name and ifstatements are for.

win32api.GetUserName()

win32api.GetUserNameEx(...) 

See: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html


回答 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

结合pwdgetpass方法,基于其他答案:

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

我前段时间编写了plx模块,以便以可移植的方式在Unix和Windows上获取用户名(以及其他功能):http : //www.decalage.info/zh-cn/python/plx

用法:

import plx

username = plx.get_username()

(在Windows上需要win32扩展名)

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

您可以通过Windows API获得Windows上的当前用户名,尽管通过ctypes FFI(GetCurrentProcessOpenProcessTokenGetTokenInformationLookupAccountSid)调用有点麻烦。

我编写了一个小模块,可以直接从Python进行此操作,即getuser.py。用法:

import getuser
print(getuser.lookup_username())

它可以在Windows和* nix上使用(后者使用pwd其他答案中所述的模块)。

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 (GetCurrentProcessOpenProcessTokenGetTokenInformationLookupAccountSid).

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).