简体   繁体   English

python:os.getenv用sudo返回none?

[英]python: os.getenv returns none with sudo?

I've set environment variable LIBRARY_PATH in /etc/bash.bashrc by adding export LIBRARY_PATH=/usr/local/cuda/lib64:$LIBRARY_PATH at the end. 我在/etc/bash.bashrc设置了环境变量LIBRARY_PATH ,最后添加了export LIBRARY_PATH=/usr/local/cuda/lib64:$LIBRARY_PATH

When I try to get the env-variable from python: 当我尝试从python获取env变量时:

ipython
import os
print os.getenv('LIBRARY_PATH')

Everything works well, it prints /usr/local/cuda/lib64: . 一切运作良好,它打印/usr/local/cuda/lib64: .

BUT when I invoke ipython with sudo : 但是当我用sudo调用ipython时:

sudo ipython
import os
pront os.getenv('LIBRARY_PATH')

I get nothing. 我一无所获。 I guess this is about env-variables accross users, but what is the ditails? 我想这是关于用户的env变量,但是什么是ditails? I set LIBRARY_PATH in /etc/bash.bashrc which is said to be the 'system wide bashrc file'. 我在/etc/bash.bashrc中设置LIBRARY_PATH ,这被称为'系统范围的bashrc文件'。

So how can I get the correct env-variable with sudo in python ? 那么如何在python中使用sudo获取正确的env变量?

If you want sudo to pass through environment variables (which is generally considered a security hazard), use sudo -E . 如果您希望sudo通过环境变量(通常被认为是安全隐患),请使用sudo -E

Note that it is bash which executes the commands in the bashrc files. 请注意,它是执行bashrc文件中的命令的bash ipython is not bash , obviously, and sudo does not start up a shell process, much less a bash process, just in order to run the command you are requesting it to run. 显然, ipython不是bash ,并且sudo不启动shell进程,更不用说bash进程了,只是为了运行你请求它运行的命令。 So none of your bashrc files are going to be executed by the sudo command or in the sudo subprocess. 因此,没有任何bashrc文件将由sudo命令或sudo子进程执行。 Of course, you can tell sudo to run a bash process: 当然,你可以告诉sudo运行一个bash进程:

sudo bash -c ipython

However, bash does not execute startup files if it detects that it is being run in a sudo process. 但是,如果bash检测到它正在sudo进程中运行,则它不会执行启动文件。

For more information on how sudo cleans the environment, type man 5 sudoers and skip down to the Command environment section. 有关sudo如何清理环境的更多信息,请键入man 5 sudoers并跳至Command environment部分。

如果在/root/.bash_profile中设置环境变量,那么在使用sudo时可能会获得所需的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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