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
2009-12-09 05:06:50
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
2009-12-09 05:14:03
Yes, not what I was looking for, but good to know nevertheless.
miracle2k
2009-12-11 07:45:03
+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
2009-12-10 19:07:58