Is there a portable way to get the current user\'s username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid
You can probably use:
os.environ.get('USERNAME')
or
os.environ.get('USER')
But it's not going to be safe because environment variables can be changed.
To me using os
module looks the best for portability: Works best on both Linux and Windows.
import os
# Gives user's home directory
userhome = os.path.expanduser('~')
print "User's home Dir: " + userhome
# Gives username by splitting path based on OS
print "username: " + os.path.split(userhome)[-1]
Output:
Windows:
User's home Dir: C:\Users\myuser
username: myuser
Linux:
User's home Dir: /root
username: root
No need of installing any modules or extensions.
Using only standard python libs:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
Works on Windows, Mac or Linux
Alternatively, you could remove one line with an immediate invocation:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
You can also use:
os.getlogin()
If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
Also you could parse such string to get only last path component (ie. user name).
See: os.path.expanduser
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)