简体   繁体   中英

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.

When I try to get the env-variable from python:

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

Everything works well, it prints /usr/local/cuda/lib64: .

BUT when I invoke ipython with sudo :

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? I set LIBRARY_PATH in /etc/bash.bashrc which is said to be the 'system wide bashrc file'.

So how can I get the correct env-variable with sudo in python ?

If you want sudo to pass through environment variables (which is generally considered a security hazard), use sudo -E .

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

However, bash does not execute startup files if it detects that it is being run in a sudo process.

For more information on how sudo cleans the environment, type man 5 sudoers and skip down to the Command environment section.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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