I am trying to run a Pipenv python instance as root. When not run as root:

(myenv) $ python script.py

the Pipenv python is correctly used. However, when run as root with sudo:

(myenv) $ sudo python script.py

the system default python at /usr/bin/python is used instead. After some searching, I found the -E option for sudo. However, with

(myenv) $ sudo -E python script.py

it still uses /usr/bin/python, even though sudo -E echo $PATH gives the same as echo $PATH, so the -E option works fine; however, sudo -E which python continues to give /usr/bin/python! It is not a permissions or access problem because the full path to the Pipenv python works fine. Why is the wrong binary being used even though $PATH is set correctly?

  • sudo won't use your pyenv environment.
    – Thomas Ward
    Sep 7, 2019 at 20:31

1 Answer 1


Ok, here's the problem. When I was troubleshooting, I wanted to find the value of $PATH inside sudo. However, with sudo -E echo $PATH, my user (non-sudo) shell was expanding it automatically, so sudo just saw

echo /home/user/.local/share/virtualenvs/environment-_Sko9eTd/bin:/usr/bin/:......

Trying sudo -E env tells us the real story:

# more environment variables ...
# ^^ doesn't include my Pipenv path

so in fact, sudo -E was not passing $PATH. To fix this you can then see this answer on a similar question. Essentially you just add

Defaults env_reset
Defaults env_keep += "PATH PYTHONPATH"

to your sudoers file with visudo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.