Home > Back-end >  In python how to get normal username from the root user?
In python how to get normal username from the root user?

Time:09-29

When I want a user directory as a normal user in Python3, from terminal

>>> os.path.expanduser('~')
/home/user

When I run in the root (sudo su)

 >>> os.path.expanduser('~')
    /root/

Is there any way to get the /home/user directory from the root user in python3?

CodePudding user response:

os.path.expanduser('~{user}')

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

os.path.expanduser('~user')

CodePudding user response:

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

CodePudding user response:

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

format, it will run in whatever directory you want.

  • Related