PYTHONPATH not working for sudo on GNU/Linux (work

2019-01-18 21:08发布

EDIT: Works for root, sudo is the problem. Read below.

I have a directory with my own libraries, e.g. my Python libraries are located at /home/name/lib/py.
I've added this directory to Python's PATH for all users (including root) by adding the following line to /etc/bash.bashrc:

export PYTHONPATH=$PYTHONPATH:/home/name/lib/py

It works for all users (including root). But it doesn't work for sudo. Is there any way I can make sudo use /etc/bash.bashrc?

EDIT: More information:

I've added PYTHONPATH to sudoers file like so: Defaults env_keep += "HOME PYTHONPATH". It sitll doesn't work.

env | grep PYTHON:
    PYTHONDONTWRITEBYTECODE=1
    PYTHONPATH=/home/name/lib/py

sudo env | grep PYTHON:
    PYTHONDONTWRITEBYTECODE=1

sudo echo $PYTHONPATH:
    /home/name/lib/py

5条回答
ゆ 、 Hurt°
2楼-- · 2019-01-18 21:45

Another tip:

sudo echo $PYTHONPATH:
    /home/name/lib/py

It won't work. Shell will interpret it like this:

1) expand $PYTHONPATH from env variable for example: /usr/lib/python

2) execute "sudo echo /usr/lib/python"

查看更多
孤傲高冷的网名
3楼-- · 2019-01-18 21:47

The same is true for the PATH variable, it's also not carried into the super user environment, even though you're passing the preserve environment flag -E.

I'm using this sudo command now without any other modifications:

sudo -HE env PATH=$PATH PYTHONPATH=$PYTHONPATH ./bin/myscript

Since it's an alternative approach that works (for me) I thought I'd share here.

查看更多
Deceive 欺骗
4楼-- · 2019-01-18 21:50

This should probably be posted somewhere else. But sudo will not process the environment file by default. If you want to invoke that the -i flag should help you out. It will simulate that users initial login.

You may have to play around with where you're putting your variables too. http://linux.die.net/man/8/sudo

查看更多
萌系小妹纸
5楼-- · 2019-01-18 22:02

The fix in my case was to remove Defaults !env_reset from sudoers.

But, I had to keep Defaults env_keep += "PYTHONPATH" in sudoers.
I've actually added Defaults env_reset (which resets environment variables), but it still works because of env_keep.

It seems that env_keep and !env_reset conflict with eachother, but that's just a guess.


So, the whole process:

  1. add export PYTHONPATH=/your/custom/path to ~/.bashrc or /etc/bash.bashrc
  2. add PYTHONPATH to Defaults env_keep += "ENV1 ENV2 ..." in sudoers file
  3. remove Defaults !env_reset from sudoers file if present
查看更多
\"骚年 ilove
6楼-- · 2019-01-18 22:05

Alternatives to manipulating PYTHONPATH:

查看更多
登录 后发表回答