Search code examples
pythonvirtualenv

Automatically load a virtualenv when running a script


I have a python script that needs dependencies from a virtualenv. I was wondering if there was some way I could add it to my path and have it auto start it's virtualenv, run and then go back to the system's python.

I've try playing around with autoenv and .env but that doesn't seem to do exactly what I'm looking for. I also thought about changing the shabang to point to the virtualenv path but that seems fragile.


Solution

  • There are two ways to do this:

    1. Put the name of the virtual env python into first line of the script. Like this

      #!/your/virtual/env/path/bin/python

    2. Add virtual environment directories to the sys.path. Note that you need to import sys library. Like this

      import sys

      sys.path.append('/path/to/virtual/env/lib')

    If you go with the second option you might need to add multiple paths to the sys.path (site etc). The best way to get it is to run your virtual env python interpreter and fish out the sys.path value. Like this:

    /your/virtual/env/bin/python
    
    Python blah blah blah
    
    > import sys
    > print sys.path
    [ 'blah', 'blah' , 'blah' ]
    

    Copy the value of sys.path into the snippet above.