miracle2k miracle2k - 5 months ago 34
Python Question

Python: Determine if running inside virtualenv

Is it possible to determine if the current script is running inside a virtualenv environment?


AFAIK the most reliable way to check for this (and the way that is used internally in virtualenv and in pip) is to check for the existence of sys.real_prefix:

import sys

if hasattr(sys, 'real_prefix'):

Inside a virtualenv, sys.prefix points to the virtualenv directory, and sys.real_prefix points to the "real" prefix of the system Python (often /usr or /usr/local or some such).

Outside a virtualenv, sys.real_prefix should not exist.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set.