How to Check if Python is Running in a Virtual Environment
Detecting whether your script runs inside a venv, virtualenv, or conda environment is essential for path configuration, dependency management, and ensuring your application uses the correct packages.
Comparing System Prefixes
The most reliable method compares sys.prefix (the current environment) with sys.base_prefix (the base Python installation). These values differ when a virtual environment is active.
import sys
def is_virtual_environment():
return sys.prefix != sys.base_prefix
if is_virtual_environment():
print(f"Virtual environment: {sys.prefix}")
else:
print("Running in global system Python")
This approach works regardless of how Python was invoked, even when calling the virtual environment's Python binary directly without activating the shell.
This is the same check Python uses internally to determine virtual environment status, making it the most reliable detection method.
Checking Environment Variables
Environment variables provide additional context about which type of virtual environment is active:
import os
def get_environment_type():
if os.getenv("VIRTUAL_ENV"):
return "venv/virtualenv"
elif os.getenv("CONDA_PREFIX"):
return "conda"
elif os.getenv("PYENV_VIRTUAL_ENV"):
return "pyenv-virtualenv"
return None
env_type = get_environment_type()
if env_type:
print(f"Running in {env_type} environment")
Environment variables are only set when you activate the environment. If you run the virtual environment's Python binary directly (e.g., ./venv/bin/python script.py), these variables won't exist even though you're technically using the virtual environment.
Comprehensive Detection Function
Combine both methods for robust detection across all scenarios:
import sys
import os
def get_virtual_env_info():
"""Detect virtual environment status and type."""
info = {
"is_virtual": sys.prefix != sys.base_prefix,
"type": None,
"path": None
}
if not info["is_virtual"]:
return info
info["path"] = sys.prefix
# Determine environment type
if os.getenv("CONDA_PREFIX"):
info["type"] = "conda"
elif os.getenv("VIRTUAL_ENV"):
info["type"] = "venv"
else:
# Activated via direct binary call
info["type"] = "venv (not activated)"
return info
env_info = get_virtual_env_info()
print(env_info)
Output:
{'is_virtual': True, 'type': 'venv', 'path': '/home/user/project/.venv'}
Practical Use Case: Dependency Verification
Use environment detection to warn users running scripts outside the expected environment:
import sys
def require_virtual_environment():
if sys.prefix == sys.base_prefix:
print("Warning: Running outside virtual environment.")
print("Run: source venv/bin/activate")
sys.exit(1)
require_virtual_environment()
# Continue with application logic...
Detection Methods Comparison
| Method | Detects Active Env | Detects Direct Binary | Identifies Type |
|---|---|---|---|
sys.prefix != sys.base_prefix | ✅ | ✅ | ❌ |
VIRTUAL_ENV variable | ✅ | ❌ | ✅ |
CONDA_PREFIX variable | ✅ | ❌ | ✅ |
Summary
Use sys.prefix != sys.base_prefix for reliable detection in application logic: it works in all scenarios including direct binary execution. Use environment variables when you need to identify the specific type of virtual environment or when writing shell scripts that interact with Python environments.