什么是获取当前用户的用户名的可移植方法(例如Linux和Windows) ?类似于os.getuid()的东西会很好:

>>> os.getuid()
42

# Does not currently exist in Python
>>> os.getusername()
'slartibartfast'

pwd模块仅适用于Unix。有些人认为,在某些情况下,在Windows下获取用户名可能会很复杂(例如,作为Windows服务运行)。


当前回答

只使用标准的python库:

from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()

适用于Windows(如果您在C盘),Mac或Linux

或者,你可以通过立即调用删除一行:

from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()

其他回答

这对我来说很管用:

import os
os.cmd("whoami")
print (os.cmd("whoami"))

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

用法:

import plx

username = plx.get_username()

(在Windows上需要win32扩展)

Psutil提供了一种可移植的方法,它不像getpass解决方案那样使用环境变量。它不太容易出现安全问题,应该是目前公认的答案。

import psutil

def get_username():
    return psutil.Process().username()

在底层,它结合了unix的基于getpuid的方法和Windows的GetTokenInformation方法。

结合os.getuid()和pwd. getpwid ():

import os
import pwd

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

有关更多细节,请参阅pwd文档。

这些可能有用。我不知道它们作为服务运行时表现如何。它们是不可移植的,但这就是os.name和ifstatement的用途。

win32api.GetUserName()

win32api.GetUserNameEx(...) 

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