【发布时间】:2021-07-15 00:38:29
【问题描述】:
我需要以 root 权限运行脚本,但 python3 有不同的行为:
在 ubuntu 中我得到:
/ubuntu/server$ sudo python3
[sudo] password for myuser:
Python 3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pathlib
>>> pathlib.Path.home()
PosixPath('/home/myuser')
在 CentOS 中是;
[centos@localhost ~]$ sudo python3
Python 3.6.8 (default, Aug 24 2020, 17:57:11)
[GCC 8.3.1 20191121 (Red Hat 8.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pathlib
>>> pathlib.Path.home()
PosixPath('/root')
如何获取Centos中sudo python的用户路径?
【问题讨论】:
-
如果没有其他方法,
os.environ['SUDO_UID']应该给你他们的 uid,你可以在/etc/passwd中查找。 -
HTF 的答案是正确的——但更明确地说:你的 Ubuntu 实例上的行为是异常值;
PosixPath('/root')是预期的默认值。