python - 在 CentOS 中以 root 身份运行 python3

标签 python linux centos

我需要以 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 的用户的路径?

最佳答案

code 中的底层逻辑将尝试检查 HOME变量来获取 homedir在 POSIX 系统上。您可以使用 sudo -E python3sudo --preserve-env=HOME python3保存它。
男人须藤:

-E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.

--preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment.


检查您的 Ubuntu 系统上是否设置了别名,例如:
$ alias sudo="sudo -E"
$ type -a sudo
sudo is aliased to `sudo -E'
sudo is /usr/bin/sudo
sudo is /bin/sudo

关于python - 在 CentOS 中以 root 身份运行 python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67185314/

相关文章:

python - 当我们有多指标时如何用实际值绘制预测值

linux - 启动数据库 : mongod failed

linux - 运行脚本中的权限被拒绝

不幸的是,当控制台关闭时,Linux 正在运行的程序会再次显示

mysql - systemctl无法在centos 7上启动mysql

python - Django 找不到 psycopg2 模块

python - Django:搜索相关模型

python - 网页抓取时如何切换框?

linux - 关于 su 命令的查询

sed - 如何从文本文件中删除多行,包括匹配的行?