views:

213

answers:

2

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

+2  A: 

When running in a virtualenv, this code shouldn't throw KeyError and give you the environment path:

>>> import os
>>> os.environ['VIRTUAL_ENV']
'/Users/you/ve/py26'

And this is how you tell you're under virtualenv (provided it was activated with bin/activate, see the comment below).

Pavel Repin
This only works if the virtualenv is activated via the bin/activate script. If you use one of the other commands in the bin directory instead, it doesn't set the environment variable.
Nicholas Riley
Yes, not what I was looking for, but good to know nevertheless.
miracle2k
+7  A: 

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.

Carl Meyer