Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate python virtual environment by shell script [duplicate]

I wrote a shell script as.

    source ve/bin/activate

Saved it as activate_shell.sh latter when I ran the script with command.

    bash activate_shell.sh

The script is being run with no error but the virtual environment is not being activated.

like image 694
Sar009 Avatar asked Dec 05 '13 05:12

Sar009


People also ask

How do I enable a Python virtual environment from a script?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .


2 Answers

Your activation script path, ve/bin/activate, is relative. The script will only work from one directory. But the problem is not here.

What does bin/activate do? It modifies the shell in which it runs. This is why you have to source it and not invoke as a regular program.

The script you wrote starts its own copy of shell (bash), activates the virtual environment inside it, and exits, destroying the just-activated environment. If your script invoked Python after sourcing the bin/activate, it would be the Python from the virtual environment, not the system one.

If you want a simple, easy-to-type command to activate a virtualenv, define a shell function:

ve() { source $1/bin/activate; }

(Yes, type the above line right into your shell prompt.)

Then type ve foo and virtualenv named foo will be activated in your current shell, provided that you're in the right directory.

Should you need to cope with a massive amount of virtualenvs, take a look at virtualenvwrapper.

like image 55
9000 Avatar answered Sep 28 '22 03:09

9000


Using a script to run source command defeats its purpose as bash activate_shell.sh will create another shell. All modification by the active command would modify the newly created shell, which terminate upon completion of your activate_shell.sh script.

A easy way to do this is to add alias to your .bash_profile instead:

alias activate_shell="source ve/bin/activate"
like image 44
marcoseu Avatar answered Sep 28 '22 04:09

marcoseu