How do I get the user home directory when running a Python script under sudo?
Question:
Using a Python SDK, I have developed an application that I run from a terminal, since some library I used required me to run this command on sudo
.
Application creates a folder by creating a project name, and stores all data in the folde
In my case, when I run sudo python app.py
, I am getting root
directory instead of home directory /home/<user_name>/
In Python, how do I get the /home/user/
?
Please note that I only have one user.
Answers:
cd /home/user && sudo python3 main.py
format, it will run in whatever directory you want.
os.path.expanduser('~{user}')
Where {user} is any user, in your case…user:
os.path.expanduser('~user')
I think that what you want is os.getlogin()
or even better getpass.getlogin()
. According to the standard library documentation for os.login()
:
For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.
So if you want to pay attention to the environment variables, use getpass.getlogin()
else prefere os.getlogin()
Using a Python SDK, I have developed an application that I run from a terminal, since some library I used required me to run this command on sudo
.
Application creates a folder by creating a project name, and stores all data in the folde
In my case, when I run sudo python app.py
, I am getting root
directory instead of home directory /home/<user_name>/
In Python, how do I get the /home/user/
?
Please note that I only have one user.
cd /home/user && sudo python3 main.py
format, it will run in whatever directory you want.
os.path.expanduser('~{user}')
Where {user} is any user, in your case…user:
os.path.expanduser('~user')
I think that what you want is os.getlogin()
or even better getpass.getlogin()
. According to the standard library documentation for os.login()
:
For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.
So if you want to pay attention to the environment variables, use getpass.getlogin()
else prefere os.getlogin()