whoami in python [duplicate]

早过忘川 提交于 2019-12-18 01:26:08

问题


What is the best way to find out the user that a python process is running under?

I could do this:

name = os.popen('whoami').read() 

But that has to start a whole new process.

os.environ["USER"]

works sometimes, but sometimes that environment variable isn't set.


回答1:


import getpass
print getpass.getuser()

See the documentation of the getpass module.

getpass.getuser()

Return the “login name” of the user. Availability: Unix, Windows.

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.




回答2:


This should work under Unix.

import os
print os.getuid() # numeric uid
import pwd
print pwd.getpwuid(os.getuid()) # full /etc/passwd info


来源:https://stackoverflow.com/questions/860140/whoami-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!