33

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.

1
  • 3
    A very simple way would be to just create a shell script that executes it for you. Just put path/to/venv/python path/to/script.py on the first line, chmod +x the new script and execute it that way. Commented May 15, 2014 at 13:06

8 Answers 8

30
+50

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.

4
  • I tried this but I am getting an error "Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007faa4f852700 (most recent call first): Aborted" It is still not able to find the python
    – Gopinath S
    Commented Nov 9, 2018 at 23:29
  • Which method did you try? First or Second? What's your sys.path?
    – Vlad
    Commented Nov 10, 2018 at 1:15
  • Worked like a charm in my virtual environment with Python 3.6.4. For the record I went for the first option and typed the Python path of my virtual environment, something like: #!C:\Temp\Users\Python scripts\env\Scripts\python.exe then went to powershell and then I executed the script in Powershell.
    – abautista
    Commented Nov 21, 2018 at 21:40
  • 2
    This assumes that the environment is already created. In the repos I work on, you only get a requirements.txt out of the box. Running the venv is required from the user.
    – Gauthier
    Commented Sep 2, 2020 at 13:51
15

I'm surprised that nobody has mentioned this yet, but this is why there is a file called activate_this.py in the virtualenv's bin directory. You can pass that to execfile() to alter the module search path for the currently running interpreter.

# doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

You can put this file at the top of your script to force the script to always run in that virtualenv. Unlike the modifying hashbang, you can use relative path with by doing:

script_directory = os.path.dirname(os.path.abspath(__file__))
activate_this_file = os.path.join(script_directory, '../../relative/path/to/env/bin/activate_this.py')
5
  • Hi I am trying to run Activitywatch on startup on Ubuntu 16.04 . The program runs on virtualenv and have to souce it using the command source ./venv/bin/activate and then running aw-qt . Can you please guide me on how to run this on starup .
    – Anoop D
    Commented Sep 6, 2018 at 3:06
  • @AnoopD: assuming aw-qt is a python script, you can run /path/to/venv/bin/python /path/to/aw-qt
    – Lie Ryan
    Commented Sep 6, 2018 at 3:13
  • I just created a file [email protected] in /etc/systemd/system/ and entered [Unit] Description=Activity Watch [Service] ExecStart=/home/anoopd/venv/bin/aw-qt [Install] WantedBy=multi-user.target But this is not working .
    – Anoop D
    Commented Sep 6, 2018 at 3:21
  • @AnoopD: you really should create a new question, it's hard to answer properly here in the comment section.
    – Lie Ryan
    Commented Sep 6, 2018 at 3:31
  • Sure , Please have a look at askubuntu.com/questions/1072607/autostart-activitywatch-16-04
    – Anoop D
    Commented Sep 6, 2018 at 4:14
10

From the virtualenv documentation:

If you directly run a script or the python interpreter from the virtualenv’s bin/ directory (e.g. path/to/env/bin/pip or /path/to/env/bin/python script.py) there’s no need for activation.

So if you just call the python executable in your virtualenv, your virtualenv will be 'active'. So you can create a script like this:

#!/bin/bash

PATH_TO_MY_VENV=/opt/django/ev_scraper/venv/bin

$PATH_TO_MY_VENV/python -c 'import sys; print(sys.version_info)'
python -c 'import sys; print(sys.version_info)'

When I run this script on my system, the two calls to python print what you see below. (Python 3.2.3 is in my virtualenv, and 2.7.3 is my system Python.)

sys.version_info(major=3, minor=2, micro=3, releaselevel='final', serial=0)
sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

So any libraries you have installed in your virtualenv will be available when you call $PATH_TO_MY_VENV/python. Calls to your regular system python will of course be unaware of whatever is in the virtualenv.

3

I think the best answer here is to create a simple script and install it inside your virtualenv. Then you can either directly use the script, or create a symlink, or whatever.

Here's an example:

$ mkdir my-tool
$ cd my-tool
$ mkdir scripts
$ touch setup.py
$ mkdir scripts
$ touch scripts/crunchy-frog
$ chmod +x scripts/crunchy-frog

crunchy-frog

#!/usr/bin/env python
print("Constable Parrot ate one of those!")

setup.py

from setuptools import setup

setup(name="my-cool-tool",
      scripts=['scripts/crunchy-frog'],
      )

Now:

$ source /path/to/my/env/bin/activate
(env) $ python setup.py develop 
(env) $ deactivate
$ cd ~
$ ln -s /path/to/my/env/bin/crunchy-frog crunchy-frog
$ ./crunchy-frog
Constable Parrot ate one of those!

When you install your script (via setup.py install or setup.py develop) then it will replace the first line of the scripts with a shebang line for the env python (which you can verify with $ head /path/to/my/env/bin/crunchy-frog). So whenever you run that particular script, it will use that specific Python env.

0

Another way to achieve it is to enforce the script to run itself through the virtual environment's interpreter, replacing its own process (os.execv), if it's currently run through a different interpreter:

#!/usr/bin/env python3
import sys
import os
venv_py=os.path.abspath("virtualenv/bin/python3")
if sys.executable != venv_py:
    os.execv(venv_py, [venv_py]+sys.argv)
-1

Does this help?

import site
site.addsitedir('/path/to/virtualenv/lib/python2.7/site-packages/')
-1

I had this problem before and I made a simple script to look for a virtualenv folder recursively just importing and calling a function:

script_autoenv.py

# -*- coding:utf-8 -*- 
import os, site

def locate_env(path, env_name):
    """search for a env directory name in each directory in the path"""
    if os.path.isdir(path + "/env"):
        env_26_path = '%s/%s/lib/python2.6/site-packages/' % (path, env_name)
        env_27_path = '%s/%s/lib/python2.7/site-packages/' % (path, env_name)


        if os.path.isdir(env_26_path):
            site.addsitedir(env_26_path)
            print "Virtualenv 2.6 founding"
        elif os.path.isdir(env_27_path):
            site.addsitedir(env_27_path)
            print "Virtualenv 2.7 founding"
    else:
        new_path, old_dir = os.path.split(path)
        if old_dir:
            locate_env(new_path, env_name)
        else:
            print "No envs found"

You just need to specify the script directory and the env name folder and the script do the rest:

test.py

# -*- coding:utf-8 -*-

import os
import script_autoenv
script_autoenv.locate_env(os.path.realpath(__file__), 'env')

import django
print django.VERSION

I hope it's works for you

-1

The answer may be pipenv (https://pipenv.readthedocs.io/en/latest/).

  • It will allow you to do something like:
pipenv run python main.py

to run main.py in the python environment with the specified libraries.

...Maybe is not exactly what you are looking for, but it may be worth taking a look before reinventing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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