function check_virtual_env
Detects whether the Python interpreter is running inside a virtual environment by checking system attributes.
/tf/active/vicechatdev/email-forwarder/run_service.py
13 - 15
simple
Purpose
This function determines if the current Python process is executing within a virtual environment (venv, virtualenv, or similar). It checks for the presence of 'real_prefix' (used by older virtualenv) or compares 'base_prefix' with 'prefix' (used by venv in Python 3.3+). This is useful for scripts that need to verify environment isolation, enforce virtual environment usage, or conditionally execute code based on the environment type.
Source Code
def check_virtual_env():
"""Check if we're running in a virtual environment."""
return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
Return Value
Returns a boolean value: True if the code is running inside a virtual environment, False if running in the system/global Python installation. The check uses two methods: (1) presence of sys.real_prefix attribute (virtualenv), or (2) sys.base_prefix differs from sys.prefix (venv).
Required Imports
import sys
Usage Example
import sys
def check_virtual_env():
"""Check if we're running in a virtual environment."""
return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
# Example usage
if check_virtual_env():
print("Running in a virtual environment")
else:
print("Running in system Python")
# Use in a script that requires virtual environment
if not check_virtual_env():
raise RuntimeError("This script must be run in a virtual environment")
Best Practices
- This function works with both virtualenv (older, uses real_prefix) and venv (Python 3.3+, uses base_prefix)
- The function is read-only and has no side effects, making it safe to call multiple times
- Consider using this check at the start of scripts that require dependency isolation
- Note that this may not detect all types of Python environment isolation (e.g., conda environments may behave differently)
- For conda environments, additional checks may be needed (e.g., checking for CONDA_DEFAULT_ENV environment variable)
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function main_v63 56.6% similar
-
function check_dependencies_v1 53.8% similar
-
function check_configuration_v1 52.4% similar
-
function main_v56 52.3% similar
-
function check_service_process 49.8% similar