什么是获取当前用户的用户名的可移植方法(例如Linux和Windows) ?类似于os.getuid()的东西会很好:
>>> os.getuid()
42
# Does not currently exist in Python
>>> os.getusername()
'slartibartfast'
pwd模块仅适用于Unix。有些人认为,在某些情况下,在Windows下获取用户名可能会很复杂(例如,作为Windows服务运行)。
什么是获取当前用户的用户名的可移植方法(例如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"])()
其他回答
这些可能有用。我不知道它们作为服务运行时表现如何。它们是不可移植的,但这就是os.name和ifstatement的用途。
win32api.GetUserName()
win32api.GetUserNameEx(...)
看到的: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html
对我来说,使用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 用户名:根
不需要安装任何模块或扩展。
我在一段时间前写了plx模块,以便在Unix和Windows上以可移植的方式获取用户名(以及其他东西): http://www.decalage.info/en/python/plx
用法:
import plx
username = plx.get_username()
(在Windows上需要win32扩展)
这对我来说很管用:
import os
os.cmd("whoami")
print (os.cmd("whoami"))
你还可以使用:
os.getlogin()