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