【问题标题】:Is there a portable way to get the current username in Python?是否有一种可移植的方式来获取 Python 中的当前用户名?
【发布时间】:2023-04-01 23:03:01
【问题描述】:

是否有一种可移植的方式在 Python 中获取当前用户的用户名(即至少在 Linux 和 Windows 下都可以使用的方式)。它会像os.getuid

>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'

我用谷歌搜索了一下,很惊讶没有找到明确的答案(尽管也许我只是在谷歌上搜索得不好)。 pwd 模块提供了一种相对简单的方法来实现这一点,比如在 Linux 下,但它在 Windows 上不存在。一些搜索结果表明,在某些情况下(例如,作为 Windows 服务运行),在 Windows 下获取用户名可能会很复杂,尽管我尚未对此进行验证。

【问题讨论】:

  • 它在我的 Linux 机器上不起作用!
  • import pwd, os; print pwd.getpwuid(os.getuid()).pw_gecosimport pwd, os; print pwd.getpwuid(os.getuid()).pw_name
  • getusername() 不是 os Python 模块中的有效方法:docs.python.org/2.7/library/os.html
  • @MattBruzek 这就是 OP 的重点。他在想象如果存在这样的函数,如何调用它。
  • “用户名”甚至不是一个可移植的概念。考虑一下 microPython——如果你直接在硬件上运行,就没有这样的东西。

标签:
python
portability