getting the current userid with Python

Ricardo nospam at here
Wed Aug 21 15:45:43 EDT 2002

> Is there a direct method for getting the current userid in Python? I
> am learning Python for the first time and was looking around for
> methods, but the only methods that I can find in usenet usually call
> external commands with the commands module or use the os module to get
> the value of of the USER shell environment variable.
> Those methods work, but I am trying to learn python, and somehow it
> feels like I am cheeting by using python to call a shell command (like
> whoami) that I already know. Getting the USER variable works, but what
> if you are not in a UNIX envornment where the USER variable does not
> exist?
> I've looked through the books, but I can't find anything...
> thanks for any suggestions?

You could try:

import getpass

Python 2.2 Library Reference says:
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.

This works fine for me on HP-UX & Linux..

On Win98 I don't have any of the environment variables set, thus it raises
an exception: 'ImportError: No module named pwd'.

More information about the Python-list mailing list