Python Language Checking if running inside a virtual environment


Sometimes the shell prompt doesn't display the name of the virtual environment and you want to be sure if you are in a virtual environment or not.

Run the python interpreter and try:

import sys
  • Outside a virtual, environment sys.prefix will point to the system python installation and sys.real_prefix is not defined.

  • Inside a virtual environment, sys.prefix will point to the virtual environment python installation and sys.real_prefix will point to the system python installation.

For virtual environments created using the standard library venv module there is no sys.real_prefix. Instead, check whether sys.base_prefix is the same as sys.prefix.