How to use a python virtualenv with sudo?
The issue is almost certainly that when you run sudo
, the virtualenv environment variables, aliases, functions, etc aren't being carried over.
The solution would be to explicitly run the virtual environment's Python executable with sudo
. For example if your virtualenv is ./AwesomeProject, then you could run sudo ./AwesomeProject/bin/python <script>
to use the script with the virtualenv with root privileges.
Just stumbled across this and for others who may find the same issue, Ken is correct that the env variables are not being carried over. The solution I used was to add the following lines to my script. This has the added benefit of always loading the virtual environment directly from the script. (Meaning you can use the script with crontab or launchd without any other workarounds.)
base_dir = os.path.dirname(os.path.abspath(__file__))
activate_this = os.path.join(base_dir, 'venv/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
More background here: https://virtualenv.pypa.io/en/latest/userguide.html#using-virtualenv-without-bin-python
Sometimes you need the $PATH updated because the script runs other programs. For example pypi-install needs py2dsc-deb in the PATH. This command works: sudo sh -c ". venv/bin/activate ; pypi-install $PACKAGE"