Search code examples
pythonbashvirtualenv

Python Virtualenv Check Environment


I am writing a bash script which need to start a service using virtualenv. I imagine my bash script to look like this:

#!/bin/bash
source /root/user/python-ev/bin/activate
IPYTHON_OPTS="notebook --port 8889 --profile pyspark" pyspark --master spark://701.datafireball.com:7077

However, I want to add a line between activate and IPYTHON... to make sure that the environment has been activated. Is there an environment variable / command in the shell that can tell me if I am inside a virtualenv or not, if so, which one?

I can hard-code to print the Python path, where it should point to a customized Python interpreter if I am inside the virtualenv, but I am not sure if that is the proper way to do it.


Solution

  • You can check for the environment variable VIRTUAL_ENV and see if it has the correct source path. Now if it doesn't exist then you know it's not activated. If it does, you need to check and see if it has the correct path.

    The correct bash snippet that will work to check if the variable is set or not is the following

    if [[ -z "$VIRTUAL_ENV" ]]; then
        echo "No VIRTUAL_ENV set"
    else
        echo "VIRTUAL_ENV is set"
    fi