I have a script where I need the path string of the current user. I am using os.path.expanduser("~")
. My problem is that if I execute the script as root
the path is /root
, where I wanted to have something like /home/user-name
. How can I achieve this in Python3?
This snippet
from os.path import expanduser
print(expanduser("~"))
when called as root sudo python3 test.py
returns:
/root
Update after post edit.
Use os.environ
to get the SUDO_USER
variable or as fallback USERNAME
.
Script test.py
:
import os
username = os.environ.get('SUDO_USER', os.environ.get('USERNAME'))
print(os.path.expanduser(f'~{username}'))
Execution:
$ python test.py
/home/louis
$ sudo python test.py
/home/louis
From man sudo
:
SUDO_USER Set to the login name of the user who invoked sudo.
Old answer before your edit.
Use os.path.expanduser
:)
>>> os.path.expanduser('~louis')
/home/louis
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.