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.

Asked By: sakthivel

||

Answers:

cd /home/user && sudo python3 main.py

format, it will run in whatever directory you want.

Answered By: Murat Yiğit
os.path.expanduser('~{user}')

Where {user} is any user, in your case…user:

os.path.expanduser('~user')
Answered By: Bret Hogg

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()

Answered By: Serge Ballesta
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.