import os
import platform
import subprocess
import json
def filter_isolated_environments(root_dir, min_python_version=3.6):
"""
Filters directories for isolated environments (e.g., venv, conda)
with support for older Python versions.
Args:
root_dir (str): The root directory to search.
min_python_version (int): The minimum Python version supported.
Returns:
list: A list of dictionaries, where each dictionary represents
an isolated environment and includes its path and Python version.
Returns an empty list if no suitable environments are found.
"""
isolated_environments = []
for root, dirs, files in os.walk(root_dir):
for dir_name in dirs:
potential_env_path = os.path.join(root, dir_name)
# Check for common environment directory names
if dir_name.endswith('venv') or dir_name == 'env' or dir_name == 'conda':
try:
# Check Python version inside the environment
python_version = get_python_version(potential_env_path)
if python_version and int(python_version.split('.')[0]) >= min_python_version:
isolated_environments.append({
'path': potential_env_path,
'python_version': python_version
})
except Exception as e:
# Handle potential errors (e.g., permission issues)
print(f"Error processing {potential_env_path}: {e}")
return isolated_environments
def get_python_version(env_path):
"""
Retrieves the Python version within a given environment.
Args:
env_path (str): The path to the environment directory.
Returns:
str: The Python version string (e.g., "3.7.12") or None if not found.
"""
try:
# Check for pyvenv.cfg (venv)
if os.path.exists(os.path.join(env_path, 'pyvenv.cfg')):
with open(os.path.join(env_path, 'pyvenv.cfg'), 'r') as f:
for line in f:
if "python" in line.lower():
return line.split('=')[1].strip()
# Check for conda environment file
if os.path.exists(os.path.join(env_path, 'conda-meta', 'Python-version')):
with open(os.path.join(env_path, 'conda-meta', 'Python-version'), 'r') as f:
return f.read().strip()
# Check for activate script (more robust)
if os.path.exists(os.path.join(env_path, 'Scripts', 'activate')):
try:
result = subprocess.run(['python', '-c', 'import sys; print(sys.version)'], cwd=env_path, capture_output=True, text=True, check=True)
return result.stdout.strip()
except subprocess.CalledProcessError:
pass # Fallback if python command fails within the environment
return None # Python version not found
except Exception as e:
print(f"Error getting Python version for {env_path}: {e}")
return None
if __name__ == '__main__':
# Example usage:
root_directory = '.' # Replace with your root directory
environments = filter_isolated_environments(root_directory)
if environments:
print(json.dumps(environments, indent=4)) # Print as JSON
else:
print("No suitable isolated environments found.")
Add your comment