Search code examples
pythonbashvirtualenv

How does one enter a Python virtualenv when executing a bashscript?


If one defines which version of python to use in a bash script, it would be

export PYTHON = "/path/python/python-3.5.1/bin/python"

But for Python virtualenv's, one executes these commands in the command line

cd /path/pathto/virtualenv
source activate
cd another_directory

How does one "enter" a Python virtualenv in a bash script? What is the standard approach here?


Solution

  • We have to distinguish two cases here:

    1. You want to use/call python (or python-based tools) in your bash script, but python or those tools should be taken from and run in a virtualenv
    2. You want a script that, amongst other things, lets the shell from which you call it enter the virtualenv, so that you can interactively call python (or python-based tools) inside the virtualenv

    Case 1: Using a virtualenv inside a script

    How does one "enter" a Python virtualenv in a bash script?

    Just like on the interactive bash command line:

    source /path/to/the/virtual_env/bin/activate
    

    What is the standard approach here?

    The standard approach is not to enter the virtualenv in a bash script. Instead, call python and/or the python-based commands you want to use by their full path. To make this easier and less repetitive, you can use aliases and variables.

    Case 2: Activating a virtualenv in an interactive bash session by calling a script

    There already is such a script. It's called activate and it's located in the bin directory of the virtualenv. You have to source it rather than calling it like a normal command. Only then will it run in the same session instead of in a subshell, and thus only then can it make modifications to the session that won't be lost due to the subshell terminating at the end of the script.

    So just do:

    source /path/to/the/virtual_env/bin/activate
    

    in your interactive shell session.

    But what if you want to do more than the activate script does? You can put

    source /path/to/the/virtual_env/bin/activate
    

    into a shell script. But, due to the reason mentioned above, it won't have much effect when you call your script normally. Instead, source your script to use it from an interactive session.

    Thus:

    Content of my_activate.sh

    #!/bin/bash
    
    # Do something
    # ...
    
    # then
    source /path/to/the/virtual_env/bin/activate
    
    # Do more stuff
    # ...
    

    and in your interactive session

    source my_activate.sh