Getting Home Path and Username in Python
Getting home path and username in python, were just an one liners for me so for : os.path.expanduser(”~/”) and pwd.getpwuid(os.getuid())[0] were doing the job for me, but when a friend was stuck with doing the same for multiple platforms he was facing few issues, so played a bit with it and came up with some silly code that worked for him, thought it was wroth sharing the code snippet with you guys, hoping it will get better!
Getting the home path :
import os
home = os.curdir
if ‘HOME’ in os.environ:
home = os.environ['HOME']
elif os.name == ‘posix’:
home = os.path.expanduser("~/")
elif os.name == ‘nt’:
if 'HOMEPATH' in os.environ and 'HOMEDRIVE' in os.environ:
home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
else:
home = os.environ['HOMEPATH']
Code for getting the current user :
import os
for name in (‘LOGNAME’, ‘USER’, ‘LNAME’, ‘USERNAME’):
user = os.environ.get(name)
if user:
return user
# If not user from os.environ.get()
import pwd
return pwd.getpwuid(os.getuid())[0]
#javascript#linux