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

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


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.


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"