python - os.getlogin() 和 os.environ 获取用户名的区别

标签 python linux python-3.x python-os

在 Linux 上使用 os.getlogin()os.environ 获取当前用户的用户名有区别吗?

在不同的时候,我看到有人建议查看环境变量 $USER$LOGNAME,其他时候是 os.getlogin()被推荐。

所以我很好奇:一个是首选,还是在某些情况下您会使用一个而不是另一个,或者它们只是做同一件事的两种方式?

最佳答案

更新:使用 getpass.getuser()

getpass.getuser()方便地搜索各种用户环境变量以获取用户名。这避免了 os.getlogin() 的问题列举如下。

如果您担心有人修改环境变量,请使用 pwd.getpwuid(os.getuid())[0] .

来自docs :

This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the pwd module, otherwise, an exception is raised.

In general, this function should be preferred over os.getlogin().

来自Python docs对于 os.getlogin() :

For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.

旧答案:os.getlogin() 的问题

长话短说

os.getlogin()在某些情况下运行时可能会抛出错误。使用 LOGNAME , USER , USERNAME等环境变量(在检查它们是否存在之后)是更安全的选择。如果您真的担心人们更改环境变量,那么您可以使用 pwd.getpwuid(os.getuid())[0] 从当前进程 ID 中提取用户名。 .

更长的解释

os.getlogin() 的一个问题是你不能在没有控制终端的情况下运行它。 From the docs :

os.getlogin()

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variables LOGNAME or USERNAME to find out who the user is, or pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.

如果您尝试调用 os.getlogin()没有控制终端,你会得到

OSError: [Errno 25] Inappropriate ioctl for device

所以使用 LOGNAME , USER , USERNAME等环境变量比 os.getlogin() 更安全.如果你真的担心人们改变环境变量,那么你可以使用 pwd.getpwuid(os.getuid())[0] .

关于python - os.getlogin() 和 os.environ 获取用户名的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47444178/

相关文章:

android - 在移动设备上修改和启动 linux 内核

Ubuntu 18.04 中的 PostgreSQL 奇怪行为

python - C++ 等同于 Linux 中 Python 的 time.time()?

python - python 中的 decimal.InvalidOperation

python - 如何将 pandas DataFrame 中的列取消嵌套(分解)为多行

python - 平方根 : ValueError: math domain error

python - 如何在与 input() 函数相同的行上打印一个字符串?

Python - Unicode 解码/编码

python - 如何从 python 3 中的字典值列表中删除 nan 值?

python - 当我们安装了较新版本的Python时,如何安装旧版本的Python