Running python script from inside virtualenv bin is not working

justin picture justin · Aug 15, 2012 · Viewed 100.6k times · Source

I have a script I want to be available globally. I've started it with the standard hashbang:

#! /usr/bin/env python

And linked it into the bin directory of my virtualenv:

~/environments/project/env/bin/myscript

And added that directory to my path. When I run the command:

myscript

I get an import error with one of the libraries. However, if I activate the virtual environment and run the script, it works as expected.

I've ruled out a problem with the symlink (I've also tried just moving the script inside the bin folder). I've also tried running the script with python

python ~/environments/project/env/bin/myscript

Previously I was using a script that activated the environment and then ran my script, but I was under the impression that script run from this folder should run with the virtualenv's interpretor and site-packages. Any ideas of why this might not be working or some ways I could debug this?

Answer

jdi picture jdi · Aug 15, 2012

Putting the script into the bin of your virtualenv, and then adding that bin location to your global PATH will not automatically source your virtualenv. You do need to source it first to make it active.

All that your system knows is to check that extra path for the executable and run it. There isn't anything in that script indicating a virtualenv.

You could, however, hardcode the she-bang line to your virtualenv python, in which case the site-packages will end up on the path:

#!/Users/foo/environments/project/env/bin/python

Or another option is to simply create a tiny bash wrapper that calls your original pythons script, which will allow you to leave your original script with a generic she-bang..

So if myscript.py is: #!/usr/bin/env python ...

Then you can make a myscript :

#!/bin/bash

/Users/foo/environments/project/env/bin/python myscript.py

When you do myscript, it will explicitly call your python script with the interpreter you set up.