Detecting a Python virtual environment
From PEP 668 – Marking Python base environments as “externally managed”:
A “virtual environment” now has a fairly precise definition: it uses the
pyvenv.cfgmechanism, which causessys.base_prefix != sys.prefix. […] In older versions ofvirtualenv, the mechanism is instead to set a new attribute,sys.real_prefix, and it does not use the standard library support for virtual environments, sosys.base_prefixis the same assys.prefix. So the logic for robustly detecting a virtual environment is something like:def is_virtual_environment(): return sys.base_prefix != sys.prefix or hasattr(sys, "real_prefix")