Determine if Python is running inside virtualenv
The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix
. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix
points to the virtual environment, and sys.base_prefix
is the prefix of the system Python the virtualenv was created from.
The above always works for Python 3 stdlib venv
and for recent virtualenv
(since version 20). Older versions of virtualenv
used sys.real_prefix
instead of sys.base_prefix
(and sys.real_prefix
did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix
did not ever exist. So a fully robust check that handles all of these cases could look like this:
import sys
def get_base_prefix_compat():
"""Get base/real prefix, or sys.prefix if there is none."""
return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
def in_virtualenv():
return get_base_prefix_compat() != sys.prefix
If you only care about supported Python versions and latest virtualenv
, you can replace get_base_prefix_compat()
with simply sys.base_prefix
.
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. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV
may be set in a Python process that is not actually running in that virtualenv.
Try using pip -V
(notice capital V)
If you are running the virtual env. it'll show the path to the env.'s location.
This is an improvement of the accepted answer by Carl Meyer. It works with virtualenv for Python 3 and 2 and also for the venv module in Python 3:
import sys
def is_venv():
return (hasattr(sys, 'real_prefix') or
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
The check for sys.real_prefix
covers virtualenv, the equality of non-empty sys.base_prefix
with sys.prefix
covers venv.
Consider a script that uses the function like this:
if is_venv():
print('inside virtualenv or venv')
else:
print('outside virtualenv or venv')
And the following invocation:
$ python2 test.py
outside virtualenv or venv
$ python3 test.py
outside virtualenv or venv
$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py
inside virtualenv or venv
(virtualenv2) $ deactivate
$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py
inside virtualenv or venv
(virtualenv3) $ deactivate
$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py
inside virtualenv or venv
(venv3) $ deactivate