简体   繁体   中英

How do I get the normal username from the root user in Python?

From the terminal, I want to create a user directory as a normal user in Python3

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

In my case, when I run the program as a root user ( sudo su )

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

How can I get the /home/user directory from the root user in Python3?

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

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

其中 {user} 是任何用户,在您的情况下......用户:

os.path.expanduser('~user')
cd /home/user && sudo python3 main.py

格式,它将在您想要的任何目录中运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM