问题描述
我通过添加 export LIBRARY_PATH =/usr/local/cuda/lib64:$ LIBRARY_PATH在
/etc/bash.bashrc
中设置环境变量 LIBRARY_PATH
结束.
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.
当我尝试从python获取env变量时:
When I try to get the env-variable from python:
ipython
import os
print os.getenv('LIBRARY_PATH')
一切正常,它会打印/usr/local/cuda/lib64:
.
但是当我用 sudo
调用ipython时:
BUT when I invoke ipython with sudo
:
sudo ipython
import os
pront os.getenv('LIBRARY_PATH')
我什么也没得到.我想这与整个用户的环境变量有关,但是有什么区别呢?我在/etc/bash.bashrc
中设置了 LIBRARY_PATH
,据说这是系统范围内的bashrc文件".
I get nothing. I guess this is about env-variables accross users, but what is the ditails? I set LIBRARY_PATH
in /etc/bash.bashrc
which is said to be the 'system wide bashrc file'.
那么如何在python中使用sudo获取正确的env变量?
So how can I get the correct env-variable with sudo in python ?
推荐答案
如果希望 sudo
传递环境变量(通常被认为是安全隐患),请使用 sudo -E
.
If you want sudo
to pass through environment variables (which is generally considered a security hazard), use sudo -E
.
请注意,是 bash
执行bashrc文件中的命令.显然, ipython
不是 bash
,并且 sudo
不会启动shell进程,更不用说bash进程了,只是为了运行命令您要求它运行.因此,您的bashrc文件都不会通过 sudo
命令或在 sudo
子进程中执行.当然,您可以告诉 sudo
运行bash进程:
Note that it is bash
which executes the commands in the bashrc files. 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. So none of your bashrc files are going to be executed by the sudo
command or in the sudo
subprocess. Of course, you can tell sudo
to run a bash process:
sudo bash -c ipython
但是,如果 bash
检测到它正在sudo进程中运行,则不会执行启动文件.
However, bash
does not execute startup files if it detects that it is being run in a sudo process.
有关 sudo
如何清洁环境的更多信息,请键入 man 5 sudoers
,然后跳至 Command environment
部分.
For more information on how sudo
cleans the environment, type man 5 sudoers
and skip down to the Command environment
section.
这篇关于python:os.getenv用sudo不返回任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!