Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a shell function know if it is running within a virtualenv?

How should a bash function test whether it is running inside a Python virtualenv?

The two approaches that come to mind are:

[[ "$(type -t deactivate)" != function ]]; INVENV=$?

or

[[ "x$(which python)" != "x$VIRTUAL_ENV/bin/python" ]]; INVENV=$?

(Note: wanting $INVENV to be 1 if we're inside a virtualenv, and 0 otherwise, is what forces the backward-looking tests above.)

Is there something less hacky?

like image 791
kjo Avatar asked Mar 16 '13 20:03

kjo


People also ask

How does virtualenv activate work?

First the user creates a new virtualenv with the command virtualenv myenv . This creates a directory called myenv and copies the system python binary to myenv/bin. It also adds other necessary files and directories to myenv, including a setup script in bin/activate and a lib subdirectory for modules and packages.

How do I run a script in virtualenv?

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

if [[ "$VIRTUAL_ENV" != "" ]]
then
  INVENV=1
else
  INVENV=0
fi
// or shorter if you like:
[[ "$VIRTUAL_ENV" == "" ]]; INVENV=$?

EDIT: as @ThiefMaster mentions in the comments, in certain conditions (for instance, when starting a new shell – perhaps in tmux or screen – from within an active virtualenv) this check may fail (however, starting new shells from within a virtualenv may cause other issues as well, I wouldn't recommend it).

like image 97
robertklep Avatar answered Oct 18 '22 20:10

robertklep


Actually, I just found a similar question, from which one can easily derive an answer to this one:

Python: Determine if running inside virtualenv

E.g., a shell script can use something like

python -c 'import sys; print (sys.real_prefix)' 2>/dev/null && INVENV=1 || INVENV=0

(Thanks to Christian Long for showing how to make this solution work with Python 3 also.)

EDIT: Here's a more direct (hence clearer and cleaner) solution (taking a cue from JuanPablo's comment):

INVENV=$(python -c 'import sys; print ("1" if hasattr(sys, "real_prefix") else "0")')
like image 19
kjo Avatar answered Oct 18 '22 21:10

kjo