Is it possible to determine if the current script is running inside a virtualenv environment?
Check the $VIRTUAL_ENV environment variable. The $VIRTUAL_ENV environment variable contains the virtual environment's directory when in an active virtual environment. Once you run deactivate / leave the virtual environment, the $VIRTUAL_ENV variable will be cleared/empty.
From a shell prompt, you can just do echo $VIRTUAL_ENV (or in Windows cmd.exe , echo %VIRTUAL_ENV% ). From within Python, sys. prefix provides the root of your Python installation (the virtual environment if active), and sys.
If you try to run virtualenv and find it isn't present, you can install it using pip. virtualenv.exe will likely now be found in your python installation directory under the Scripts subdirectory.
The instructions in this tutorial use Python's venv module to create virtual environments. This module is part of Python's standard library, and it's the officially recommended way to create virtual environments since Python 3.5.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With