Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

python - PYTHONPATH not working for sudo on GNU/Linux (works for root)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...