50

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.

Will Daniels
  • 274
  • 2
  • 6
Josh Gibson
  • 21,808
  • 28
  • 67
  • 63

2 Answers2

100
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.

Community
  • 1
  • 1
Ayman Hourieh
  • 132,184
  • 23
  • 144
  • 116
20

This should work under Unix.

import os
print(os.getuid()) # numeric uid
import pwd
print(pwd.getpwuid(os.getuid())) # full /etc/passwd info
WattsInABox
  • 4,548
  • 2
  • 33
  • 43
  • This solution only works on Unix see http://docs.python.org/library/pwd.html?highlight=pwd – Nadia Alramli May 13 '09 at 20:15
  • Works on my linux box, i had the same answer as this one but will delete it as i was 2 minutes later ;-) – ChristopheD May 13 '09 at 20:16
  • getpass.getuser() uses this approach as a fallback if it cannot find the username in the environment variables. – Ayman Hourieh May 13 '09 at 20:26
  • @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. –  May 14 '09 at 04:51
  • @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. –  May 14 '09 at 04:53
  • @NadiaAlramli he knows. he said so in the answer. – Cinder Jan 19 '13 at 10:53