1. import os
  2. import platform
  3. import subprocess
  4. import json
  5. def filter_isolated_environments(root_dir, min_python_version=3.6):
  6. """
  7. Filters directories for isolated environments (e.g., venv, conda)
  8. with support for older Python versions.
  9. Args:
  10. root_dir (str): The root directory to search.
  11. min_python_version (int): The minimum Python version supported.
  12. Returns:
  13. list: A list of dictionaries, where each dictionary represents
  14. an isolated environment and includes its path and Python version.
  15. Returns an empty list if no suitable environments are found.
  16. """
  17. isolated_environments = []
  18. for root, dirs, files in os.walk(root_dir):
  19. for dir_name in dirs:
  20. potential_env_path = os.path.join(root, dir_name)
  21. # Check for common environment directory names
  22. if dir_name.endswith('venv') or dir_name == 'env' or dir_name == 'conda':
  23. try:
  24. # Check Python version inside the environment
  25. python_version = get_python_version(potential_env_path)
  26. if python_version and int(python_version.split('.')[0]) >= min_python_version:
  27. isolated_environments.append({
  28. 'path': potential_env_path,
  29. 'python_version': python_version
  30. })
  31. except Exception as e:
  32. # Handle potential errors (e.g., permission issues)
  33. print(f"Error processing {potential_env_path}: {e}")
  34. return isolated_environments
  35. def get_python_version(env_path):
  36. """
  37. Retrieves the Python version within a given environment.
  38. Args:
  39. env_path (str): The path to the environment directory.
  40. Returns:
  41. str: The Python version string (e.g., "3.7.12") or None if not found.
  42. """
  43. try:
  44. # Check for pyvenv.cfg (venv)
  45. if os.path.exists(os.path.join(env_path, 'pyvenv.cfg')):
  46. with open(os.path.join(env_path, 'pyvenv.cfg'), 'r') as f:
  47. for line in f:
  48. if "python" in line.lower():
  49. return line.split('=')[1].strip()
  50. # Check for conda environment file
  51. if os.path.exists(os.path.join(env_path, 'conda-meta', 'Python-version')):
  52. with open(os.path.join(env_path, 'conda-meta', 'Python-version'), 'r') as f:
  53. return f.read().strip()
  54. # Check for activate script (more robust)
  55. if os.path.exists(os.path.join(env_path, 'Scripts', 'activate')):
  56. try:
  57. result = subprocess.run(['python', '-c', 'import sys; print(sys.version)'], cwd=env_path, capture_output=True, text=True, check=True)
  58. return result.stdout.strip()
  59. except subprocess.CalledProcessError:
  60. pass # Fallback if python command fails within the environment
  61. return None # Python version not found
  62. except Exception as e:
  63. print(f"Error getting Python version for {env_path}: {e}")
  64. return None
  65. if __name__ == '__main__':
  66. # Example usage:
  67. root_directory = '.' # Replace with your root directory
  68. environments = filter_isolated_environments(root_directory)
  69. if environments:
  70. print(json.dumps(environments, indent=4)) # Print as JSON
  71. else:
  72. print("No suitable isolated environments found.")

Add your comment