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
How Are Python'S Built in Dictionaries Implemented
Count the Frequency That a Value Occurs in a Dataframe Column
When Is "I += X" Different from "I = I + X" in Python
Adding a New Pandas Column With Mapped Value from a Dictionary
How to Convert an Integer to a String in Any Base
Why Are Python'S 'Private' Methods Not Actually Private
How to Play Wav File in Python
Is There Any Pythonic Way to Combine Two Dicts (Adding Values For Keys That Appear in Both)
How to Concatenate Text Files in Python
Save Plot to Image File Instead of Displaying It Using Matplotlib
How to Replace Nan Values by Zeroes in a Column of a Pandas Dataframe
How to Calculate Number of Days Between Two Given Dates
Choosing the Correct Upper and Lower Hsv Boundaries For Color Detection With'Cv::Inrange' (Opencv)
How to Sort a List of Objects Based on an Attribute of the Objects