views:

8483

answers:

6

Is there a portable way to get the current user's username in Python (i.e., works under both Linux and Windows, at least). It would work like os.getuid:

>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'

I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.

+29  A: 

Look at getpass module

>>> import getpass
>>> getpass.getuser()
'kostya'

Availability: Unix, Windows

Konstantin
It appears that this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other).
Greg Hewgill
Nice, not sure how I missed that!
Jacob Gabrielson
I know why _I_ missed it: the "getpass" module doesn't appear anywhere near the top of the search results in the little html-help thingy that comes with 2.6.1 when I search for "user". (I'm not sure it appears at all, for that matter.)
offby1
Works in OS X as well, btw.
dF
OS X is considered Unix for purposes of the libref.
Ignacio Vazquez-Abrams
+2  A: 

You can probably use:

os.getenv('USERNAME')

But it's not going to be safe because environment variables can be changed.

Nadia Alramli
+2  A: 

You can also use:

 os.getlogin()
Marcin Augustyniak
On linux, getlogin() returns the name of the "user logged in on the controlling terminal of the process." It therefore fails when there is no controlling terminal, e.g., in a mod_python application.
Vebjorn Ljosa
A: 

These might work. I don't know how they behave when running as a service. They aren't portable, but that's what "os.name" and "if" statements are for.

win32api.GetUserName()

win32api.GetUserNameEx(...)

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

Adam
+1  A: 

I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things): http://www.decalage.info/en/python/plx

Usage:

import plx

username = plx.get_username()

(it requires win32 extensions on Windows)

decalage
+6  A: 

You best bet would be to combine os.getuid() with pwd.getpwuid():

import os
import pwd

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

Refer to the pwd manpage for more details:

http://docs.python.org/library/pwd.html

Liam Chasteen
Alternatively (slightly nicer to read): `pwd.getpwuid(os.getuid()).pw_name`.
Brian M. Hunt