Python Bash如何在脚本中传递命令的环境
所以我有一个python脚本,它需要在环境变量中定义locale,比如:Python Bash如何在脚本中传递命令的环境,python,bash,environment-variables,Python,Bash,Environment Variables,所以我有一个python脚本,它需要在环境变量中定义locale,比如:export LC\u ALL=C.UTF-8。所以我想我只需要创建一个脚本,如下所示: #!/bin/bash export LC_ALL=C.UTF-8 sudo python3 example.py 但是python脚本抱怨环境变量设置不正确。当我在执行脚本之前手动运行这些命令或导出环境变量时,程序就会工作。这里一定有什么我没注意到的地方。好吧,理论上你做得对: 标记为export的环境变量将导出到子进程(即:
export LC\u ALL=C.UTF-8
。所以我想我只需要创建一个脚本,如下所示:
#!/bin/bash
export LC_ALL=C.UTF-8
sudo python3 example.py
但是python脚本抱怨环境变量设置不正确。当我在执行脚本之前手动运行这些命令或导出环境变量时,程序就会工作。这里一定有什么我没注意到的地方。好吧,理论上你做得对: 标记为
export
的环境变量将导出到子进程(即:从此shell启动的程序)
不过
sudo
有点不同,因为它对安全性非常敏感。
毕竟,如果使用了正确的变量(想想LD\u PRELOAD
),就可以完全改变以超级用户权限运行的命令的行为
因此,sudo
主动防止环境变量传递给sudoed进程
幸运的是(对您来说),您可以更改保留的环境变量(至少,如果系统的安全策略允许的话)
从man 8 sudo
:
-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. This option may be specified multiple times.
我认为这个问题最好是在超级用户上问。具体来说,如果我只对这个LC_ALL值感兴趣,那么
sudo--preserve env=LC_ALL python3 example.py
应该足够吗?是的。(但尝试一下真的很容易)