import os
import sys
import subprocess
import winreg
import platform
"""
How to use:
Save this as a `python_info.py` file and run it using Python.
There are various ways to run Python scripts on Windows. When your
Python installations are conflicting, or have been messed up, some
methods may work, and others may not.
* Method 1: `python_info.py` assumes that the Python executable is in
the system's PATH and that the script has a shebang line (`#! python`)
or is associated with the Python executable (*.py).
* Method 2: `python python_info.py` explicitly calls the Python
executable, which is useful if the script doesn't have a shebang line
or isn't associated with the Python executable (*.py).
* Method 3: `py python_info.py` uses the `py` launcher, which is a part
of the Python for Windows installation. It allows you to easily run
Python scripts without specifying the full path to the Python
executable.
* Method 4: `py -3.10 python_info.py` and `py -3.9 python_info.py` use
the `py` launcher to specify a particular version of Python to use.
Running this script using any method may help you fix a broken Python
installation.
"""
def run_command(command):
"""Executes a shell command and returns the output or error message."""
try:
result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
return f"Error: {e.stderr.strip()}"
def display_list(title, items):
"""Displays a list of items with a title, formatted for readability."""
print(f"{title}:\n")
if isinstance(items, list):
for item in items:
print(f" - {item}")
else:
print(f" {items}")
print()
def check_registry_paths(base_key, sub_key, base_key_name):
"""Checks specified registry paths for installed Python versions."""
python_paths = []
try:
with winreg.OpenKey(base_key, sub_key) as key:
i = 0
while True:
try:
version = winreg.EnumKey(key, i)
with winreg.OpenKey(key, f"{version}\\InstallPath") as subkey:
python_path = winreg.QueryValue(subkey, "")
python_paths.append(f"Version {version}: {python_path}")
i += 1
except OSError:
break
except PermissionError:
python_paths.append(f"Access denied to {base_key_name}. Consider running as Administrator.")
except FileNotFoundError:
python_paths.append(f"No Python installations found in {base_key_name}.")
except Exception as e:
python_paths.append(f"Error accessing {base_key_name}: {str(e)}")
return python_paths
def display_install_locations():
"""Displays the install locations for Python, py launcher, and pip."""
python_locations = run_command("where python" if os.name == 'nt' else "which python").splitlines()
py_location = run_command("where py" if os.name == 'nt' else "which py").splitlines()
pip_locations = run_command("where pip" if os.name == 'nt' else "which pip").splitlines()
display_list("Install Locations",
[f"[PYTHON] {loc}" for loc in python_locations] +
[f"[PIP] {loc}" for loc in pip_locations] +
[f"[PY] {loc}" for loc in py_location])
def display_env_variables():
"""Displays key Python-related environment variables."""
display_list("PYTHONPATH", os.environ.get('PYTHONPATH', 'Not Set'))
display_list("PY_PYTHON", os.environ.get('PY_PYTHON', 'Not Set'))
display_list("PY_PYTHON3", os.environ.get('PY_PYTHON3', 'Not Set'))
def main():
print("="*60)
print("Python Environment Information")
print("="*60, "\n")
# Get Python version
python_version = run_command(f'{sys.executable} -c "import sys; print(sys.version)"')
display_list("Python Version", python_version)
# Get Python build and compiler information
python_build = run_command(f'{sys.executable} -c "import sys; print(sys.version_info[:])"')
display_list("Python Version Info", python_build)
# Display install locations
display_install_locations()
# Display environment details
print("="*60)
print("Packages Installed")
print("="*60, "\n")
# Get paths for site-packages
user_site_packages = run_command(f'{sys.executable} -c "import site; print(site.getusersitepackages())"')
global_site_packages = run_command(f'{sys.executable} -c "import site; print(site.getsitepackages())"')
# Display user-installed packages
print("[USER]")
print(run_command(f'{sys.executable} -m pip list --user'))
print(f"\nUser Site-Packages Location: {user_site_packages}\n")
# Display globally installed packages
print("[GLOBAL]")
print(run_command(f'{sys.executable} -m pip list --local'))
print() # Add an empty line before Global Site-Packages Locations
display_list("Global Site-Packages Locations", eval(global_site_packages))
# Check for outdated packages
print("Outdated Packages:")
outdated = run_command(f'{sys.executable} -m pip list --outdated')
print(outdated if outdated else "No outdated packages found.")
print()
# Display environment details
print("="*60)
print("Environment Details")
print("="*60, "\n")
# Display current working directory
display_list("Current Working Directory", os.getcwd())
# Display more information about the Python executable
executable_info = run_command(f'{sys.executable} -c "import platform; print(platform.python_implementation(), platform.python_version())"')
display_list("Python Executable Information", [sys.executable, executable_info])
# Check if running in a virtual environment
venv = os.environ.get('VIRTUAL_ENV', 'Not in a virtual environment')
display_list("Virtual Environment", venv)
# Display environment variables
display_env_variables()
# Display PATH with numbering
path_items = list(filter(None, os.environ.get('PATH', '').split(os.pathsep)))
print("PATH:\n")
for idx, path in enumerate(path_items, start=1):
print(f" [{idx}] {path}")
print()
# Display sys.path
print("Python Module Search Paths:")
print()
for idx, path in enumerate(sys.path, start=1):
print(f" [{idx}] {path}")
print()
# Check Python installations in registry
print("="*60)
print("Python Installations in Registry")
print("="*60, "\n")
user_key = winreg.HKEY_CURRENT_USER
machine_key = winreg.HKEY_LOCAL_MACHINE
sub_key = r"Software\Python\PythonCore"
# Check both HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE
display_list("HKEY_CURRENT_USER", check_registry_paths(user_key, sub_key, "HKEY_CURRENT_USER"))
display_list("HKEY_LOCAL_MACHINE", check_registry_paths(machine_key, sub_key, "HKEY_LOCAL_MACHINE"))
print("\nRecommendations:")
print("1. Ensure the desired Python version is prioritized in the PATH.")
print("2. Use 'py -X.Y' to target specific Python versions if multiple are installed.")
print("3. Consider repairing Python installations via the installer if inconsistencies are found.")
if __name__ == "__main__":
main()
Comments
0 B
|👍
/👎