tags:

views:

1039

answers:

2
+2  Q: 

whoami in python

Duplicate of: Is there a portable way to get the current username in Python?


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.

+7  A: 

This should work under Unix.

import os
print os.getuid() # numeric uid
import pwd
print pwd.getpwuid(os.getuid()) # full /etc/passwd info
Lars Wirzenius
This solution only works on Unix see http://docs.python.org/library/pwd.html?highlight=pwd
Nadia Alramli
Works on my linux box, i had the same answer as this one but will delete it as i was 2 minutes later ;-)
ChristopheD
getpass.getuser() uses this approach as a fallback if it cannot find the username in the environment variables.
Ayman Hourieh
@Ayman: I find it better to rely on os.getuid than environment variables to figure out who I am. Environment variables are untrustworthy, especially if security matters.
Lars Wirzenius
@Nadia: Aye, it probably doesn't work on Windows, but the question is tagged posix, and os.getuid and pwd.getpwuid are both part of Posix.
Lars Wirzenius
+10  A: 
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.

Ayman Hourieh
That's so great, I didn't know that stuff.
e-satis