Advertisement
J2897

python_info

Aug 31st, 2024 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.41 KB | None | 0 0
  1. import os
  2. import sys
  3. import subprocess
  4. import winreg
  5. import platform
  6.  
  7. """
  8.    How to use:
  9.  
  10.    Save this as a `python_info.py` file and run it using Python.
  11.  
  12.    There are various ways to run Python scripts on Windows. When your
  13.    Python installations are conflicting, or have been messed up, some
  14.    methods may work, and others may not.
  15.  
  16.    * Method 1: `python_info.py` assumes that the Python executable is in
  17.    the system's PATH and that the script has a shebang line (`#! python`)
  18.    or is associated with the Python executable (*.py).
  19.  
  20.    * Method 2: `python python_info.py` explicitly calls the Python
  21.    executable, which is useful if the script doesn't have a shebang line
  22.    or isn't associated with the Python executable (*.py).
  23.  
  24.    * Method 3: `py python_info.py` uses the `py` launcher, which is a part
  25.    of the Python for Windows installation. It allows you to easily run
  26.    Python scripts without specifying the full path to the Python
  27.    executable.
  28.  
  29.    * Method 4: `py -3.10 python_info.py` and `py -3.9 python_info.py` use
  30.    the `py` launcher to specify a particular version of Python to use.
  31.  
  32.    Running this script using any method may help you fix a broken Python
  33.    installation.
  34. """
  35.  
  36. def run_command(command):
  37.     """Executes a shell command and returns the output or error message."""
  38.     try:
  39.         result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  40.         return result.stdout.strip()
  41.     except subprocess.CalledProcessError as e:
  42.         return f"Error: {e.stderr.strip()}"
  43.  
  44. def display_list(title, items):
  45.     """Displays a list of items with a title, formatted for readability."""
  46.     print(f"{title}:\n")
  47.     if isinstance(items, list):
  48.         for item in items:
  49.             print(f"  - {item}")
  50.     else:
  51.         print(f"  {items}")
  52.     print()
  53.  
  54. def check_registry_paths(base_key, sub_key, base_key_name):
  55.     """Checks specified registry paths for installed Python versions."""
  56.     python_paths = []
  57.     try:
  58.         with winreg.OpenKey(base_key, sub_key) as key:
  59.             i = 0
  60.             while True:
  61.                 try:
  62.                     version = winreg.EnumKey(key, i)
  63.                     with winreg.OpenKey(key, f"{version}\\InstallPath") as subkey:
  64.                         python_path = winreg.QueryValue(subkey, "")
  65.                         python_paths.append(f"Version {version}: {python_path}")
  66.                     i += 1
  67.                 except OSError:
  68.                     break
  69.     except PermissionError:
  70.         python_paths.append(f"Access denied to {base_key_name}. Consider running as Administrator.")
  71.     except FileNotFoundError:
  72.         python_paths.append(f"No Python installations found in {base_key_name}.")
  73.     except Exception as e:
  74.         python_paths.append(f"Error accessing {base_key_name}: {str(e)}")
  75.     return python_paths
  76.  
  77. def display_install_locations():
  78.     """Displays the install locations for Python, py launcher, and pip."""
  79.     python_locations = run_command("where python" if os.name == 'nt' else "which python").splitlines()
  80.     py_location = run_command("where py" if os.name == 'nt' else "which py").splitlines()
  81.     pip_locations = run_command("where pip" if os.name == 'nt' else "which pip").splitlines()
  82.  
  83.     display_list("Install Locations",
  84.                  [f"[PYTHON] {loc}" for loc in python_locations] +
  85.                  [f"[PIP] {loc}" for loc in pip_locations] +
  86.                  [f"[PY] {loc}" for loc in py_location])
  87.  
  88. def display_env_variables():
  89.     """Displays key Python-related environment variables."""
  90.     display_list("PYTHONPATH", os.environ.get('PYTHONPATH', 'Not Set'))
  91.     display_list("PY_PYTHON", os.environ.get('PY_PYTHON', 'Not Set'))
  92.     display_list("PY_PYTHON3", os.environ.get('PY_PYTHON3', 'Not Set'))
  93.  
  94. def main():
  95.     print("="*60)
  96.     print("Python Environment Information")
  97.     print("="*60, "\n")
  98.  
  99.     # Get Python version
  100.     python_version = run_command(f'{sys.executable} -c "import sys; print(sys.version)"')
  101.     display_list("Python Version", python_version)
  102.  
  103.     # Get Python build and compiler information
  104.     python_build = run_command(f'{sys.executable} -c "import sys; print(sys.version_info[:])"')
  105.     display_list("Python Version Info", python_build)
  106.  
  107.     # Display install locations
  108.     display_install_locations()
  109.  
  110.     # Display environment details
  111.     print("="*60)
  112.     print("Packages Installed")
  113.     print("="*60, "\n")
  114.  
  115.     # Get paths for site-packages
  116.     user_site_packages = run_command(f'{sys.executable} -c "import site; print(site.getusersitepackages())"')
  117.     global_site_packages = run_command(f'{sys.executable} -c "import site; print(site.getsitepackages())"')
  118.  
  119.     # Display user-installed packages
  120.     print("[USER]")
  121.     print(run_command(f'{sys.executable} -m pip list --user'))
  122.     print(f"\nUser Site-Packages Location: {user_site_packages}\n")
  123.  
  124.     # Display globally installed packages
  125.     print("[GLOBAL]")
  126.     print(run_command(f'{sys.executable} -m pip list --local'))
  127.     print()  # Add an empty line before Global Site-Packages Locations
  128.     display_list("Global Site-Packages Locations", eval(global_site_packages))
  129.  
  130.     # Check for outdated packages
  131.     print("Outdated Packages:")
  132.     outdated = run_command(f'{sys.executable} -m pip list --outdated')
  133.     print(outdated if outdated else "No outdated packages found.")
  134.     print()
  135.  
  136.     # Display environment details
  137.     print("="*60)
  138.     print("Environment Details")
  139.     print("="*60, "\n")
  140.  
  141.     # Display current working directory
  142.     display_list("Current Working Directory", os.getcwd())
  143.  
  144.     # Display more information about the Python executable
  145.     executable_info = run_command(f'{sys.executable} -c "import platform; print(platform.python_implementation(), platform.python_version())"')
  146.     display_list("Python Executable Information", [sys.executable, executable_info])
  147.  
  148.     # Check if running in a virtual environment
  149.     venv = os.environ.get('VIRTUAL_ENV', 'Not in a virtual environment')
  150.     display_list("Virtual Environment", venv)
  151.  
  152.     # Display environment variables
  153.     display_env_variables()
  154.  
  155.     # Display PATH with numbering
  156.     path_items = list(filter(None, os.environ.get('PATH', '').split(os.pathsep)))
  157.     print("PATH:\n")
  158.     for idx, path in enumerate(path_items, start=1):
  159.         print(f"  [{idx}] {path}")
  160.     print()
  161.  
  162.     # Display sys.path
  163.     print("Python Module Search Paths:")
  164.     print()
  165.     for idx, path in enumerate(sys.path, start=1):
  166.         print(f"  [{idx}] {path}")
  167.     print()
  168.  
  169.     # Check Python installations in registry
  170.     print("="*60)
  171.     print("Python Installations in Registry")
  172.     print("="*60, "\n")
  173.     user_key = winreg.HKEY_CURRENT_USER
  174.     machine_key = winreg.HKEY_LOCAL_MACHINE
  175.     sub_key = r"Software\Python\PythonCore"
  176.  
  177.     # Check both HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE
  178.     display_list("HKEY_CURRENT_USER", check_registry_paths(user_key, sub_key, "HKEY_CURRENT_USER"))
  179.     display_list("HKEY_LOCAL_MACHINE", check_registry_paths(machine_key, sub_key, "HKEY_LOCAL_MACHINE"))
  180.  
  181.     print("\nRecommendations:")
  182.     print("1. Ensure the desired Python version is prioritized in the PATH.")
  183.     print("2. Use 'py -X.Y' to target specific Python versions if multiple are installed.")
  184.     print("3. Consider repairing Python installations via the installer if inconsistencies are found.")
  185.  
  186. if __name__ == "__main__":
  187.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement