Is There a Portable Way to Get the Current Username in Python

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

Look at getpass module

import getpass
getpass.getuser()
'kostya'

Availability: Unix, Windows


p.s. Per comment below "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)."

How to make Python get the username in windows and then implement it in a script

os.getlogin() return the user that is executing the, so it can be:

path = os.path.join('..','Documents and Settings',os.getlogin(),'Desktop')

or, using getpass.getuser()

path = os.path.join('..','Documents and Settings',getpass.getuser(),'Desktop')

If I understand what you asked.

How do I get the username in Python?

import getpass
print getpass.getuser()

Get username of current session

The simplest way to do this on UNIX OS's is by using the "SUDO_USER" environment variable:

>>> import os
>>> os.getenv("SUDO_USER")
'test_user'

The only caveat is that this is not truly portable, for example on Fedora 17 this variable is not set (But will work for almost all environments and distros).


There is an alternative much more bulky solution that covers much more edge cases, this might work better for your use case.

import os
import shutil
import getpass
import pwd

def get_user():
"""Try to find the user who called sudo/pkexec."""
try:
return os.getlogin()
except OSError:
# failed in some ubuntu installations and in systemd services
pass

try:
user = os.environ['USER']
except KeyError:
# possibly a systemd service. no sudo was used
return getpass.getuser()

if user == 'root':
try:
return os.environ['SUDO_USER']
except KeyError:
# no sudo was used
pass

try:
pkexec_uid = int(os.environ['PKEXEC_UID'])
return pwd.getpwuid(pkexec_uid).pw_name
except KeyError:
# no pkexec was used
pass

return user

EG of working cases:

$ python3 getuser.py
test_user
$ sudo python3 getuser.py
test_user
$ pkexec python3 getuser.py
test_user


Related Topics



Leave a reply



Submit