Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to make a python environment separate from the system one (using virtualenv) in a directory which is not under /home, because I need to use it to build other software that has to be accessible to multiple users. I can create and activate the virtualenv all right, but when I sudo some command (for example to make or compile other software), it is the system python that is used (I can tell because of the available modules).

Since on Ubuntu it is not a good thing to use the root user, is there a way to tell sudo to use a virtualenv? Or maybe this is not the correct approach, and I should make a completely new python installation?

I am using the 64bit version of Ubuntu 12.04 (and python 2.7).

share|improve this question
up vote 15 down vote accepted

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.

share|improve this answer
You could also let the first line of your script point to the Python binary in your virtualenv. #!<virtualenv_dir>/bin/python. – OrangeTux Sep 17 '13 at 14:04

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/')
execfile(activate_this, dict(__file__=activate_this))

More background here:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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