PyGuide

Learn Python with practical tutorials and code examples

Code Snippet Beginner
• Updated Jul 27, 2024

Python Scripts to Detect Which Python You Have on Windows

Ready-to-use Python code snippets to detect which Python installation, version, and architecture you're running on Windows systems.

Python Scripts to Detect Which Python You Have on Windows

These code snippets help you programmatically determine which Python installation, version, and configuration you're using on Windows systems.

Basic Windows Python Detection #

Quick ways to identify which Python you're running on Windows:

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Windows Python Installation Type Detection #

Determine which type of Python installation you're using:

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Windows Python Environment Analysis #

Comprehensive analysis of your Python environment on Windows:

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Windows PATH Configuration Checker #

Check if Python is properly configured in Windows PATH:

import os
import sys
from pathlib import Path

def check_windows_python_path():
    """Check Python PATH configuration on Windows"""
    
    # Get current Python paths
    python_executable = Path(sys.executable)
    python_dir = python_executable.parent
    scripts_dir = python_dir / 'Scripts'
    
    # Get system PATH
    system_path = os.environ.get('PATH', '').split(';')
    system_path = [p.strip() for p in system_path if p.strip()]
    
    # Check PATH entries
    results = {
        'python_in_path': False,
        'scripts_in_path': False,
        'path_entries': [],
        'python_executables_found': [],
        'recommendations': []
    }
    
    # Find Python-related PATH entries
    for path_entry in system_path:
        path_lower = path_entry.lower()
        if 'python' in path_lower:
            results['path_entries'].append(path_entry)
            
            # Check for python.exe in this path
            potential_python = Path(path_entry) / 'python.exe'
            if potential_python.exists():
                results['python_executables_found'].append(str(potential_python))
        
        # Check if current Python directories are in PATH
        if str(python_dir).lower() == path_lower:
            results['python_in_path'] = True
        if str(scripts_dir).lower() == path_lower:
            results['scripts_in_path'] = True
    
    # Generate recommendations
    if not results['python_in_path']:
        results['recommendations'].append(f"Add to PATH: {python_dir}")
    if not results['scripts_in_path']:
        results['recommendations'].append(f"Add to PATH: {scripts_dir}")
    
    if len(results['python_executables_found']) > 1:
        results['recommendations'].append("Multiple Python installations found - consider using virtual environments")
    
    return results

# Check PATH configuration
path_check = check_windows_python_path()

print("Windows Python PATH Analysis:")
print(f"Python directory in PATH: {'✅' if path_check['python_in_path'] else '❌'}")
print(f"Scripts directory in PATH: {'✅' if path_check['scripts_in_path'] else '❌'}")

print(f"\nPython executables found: {len(path_check['python_executables_found'])}")
for exe in path_check['python_executables_found']:
    print(f"  {exe}")

print(f"\nPython-related PATH entries:")
for entry in path_check['path_entries']:
    print(f"  {entry}")

if path_check['recommendations']:
    print(f"\nRecommendations:")
    for rec in path_check['recommendations']:
        print(f"  {rec}")

Windows Python Package Location Detector #

Find where packages are installed on your Windows Python:

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Windows Python Performance Checker #

Check Python performance characteristics on Windows:

import sys
import time
import platform
import gc

def check_windows_python_performance():
    """Check Python performance characteristics on Windows"""
    
    performance_info = {
        'startup_time': None,
        'import_time': None,
        'gc_stats': None,
        'memory_usage': None,
        'optimization_level': sys.flags.optimize,
        'debug_build': hasattr(sys, 'gettotalrefcount'),
        'gil_enabled': True  # Python always has GIL
    }
    
    # Measure import time
    start_time = time.perf_counter()
    import json  # Common module
    import_time = time.perf_counter() - start_time
    performance_info['import_time'] = f"{import_time * 1000:.2f} ms"
    
    # Get garbage collection stats
    gc_stats = gc.get_stats()
    performance_info['gc_stats'] = {
        'generations': len(gc_stats),
        'collections': [stat['collections'] for stat in gc_stats],
        'collected': [stat['collected'] for stat in gc_stats]
    }
    
    # Check memory usage (basic)
    try:
        import psutil
        process = psutil.Process()
        memory_mb = process.memory_info().rss / 1024 / 1024
        performance_info['memory_usage'] = f"{memory_mb:.1f} MB"
    except ImportError:
        performance_info['memory_usage'] = "psutil not available"
    
    # Windows-specific checks
    if platform.system() == 'Windows':
        # Check if running under Windows Subsystem for Linux
        performance_info['wsl'] = 'microsoft' in platform.uname().release.lower()
        
        # Check Windows version impact
        win_version = platform.win32_ver()[0]
        if win_version == '10':
            performance_info['windows_optimization'] = 'Good'
        elif win_version == '11':
            performance_info['windows_optimization'] = 'Excellent'
        else:
            performance_info['windows_optimization'] = 'Basic'
    
    return performance_info

# Check performance
perf_info = check_windows_python_performance()

print("Windows Python Performance Analysis:")
for key, value in perf_info.items():
    if key == 'gc_stats':
        print(f"Garbage Collection:")
        print(f"  Generations: {value['generations']}")
        print(f"  Collections: {value['collections']}")
        print(f"  Objects collected: {value['collected']}")
    else:
        print(f"{key.replace('_', ' ').title()}: {value}")

Windows Python Registry Detection #

Detect Python installations from Windows Registry:

import sys
import platform

def detect_python_from_registry():
    """Detect Python installations from Windows Registry"""
    
    if platform.system() != 'Windows':
        return {'error': 'This script only works on Windows'}
    
    try:
        import winreg
    except ImportError:
        return {'error': 'winreg module not available'}
    
    python_installations = []
    
    # Common registry paths for Python installations
    registry_paths = [
        (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Python\PythonCore"),
        (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Python\PythonCore"),
        (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Python\PythonCore")
    ]
    
    for hive, path in registry_paths:
        try:
            with winreg.OpenKey(hive, path) as key:
                i = 0
                while True:
                    try:
                        version = winreg.EnumKey(key, i)
                        
                        # Get installation path
                        try:
                            install_path_key = winreg.OpenKey(key, f"{version}\\InstallPath")
                            install_path = winreg.QueryValue(install_path_key, "")
                            
                            python_installations.append({
                                'version': version,
                                'path': install_path,
                                'hive': 'HKLM' if hive == winreg.HKEY_LOCAL_MACHINE else 'HKCU',
                                'registry_path': f"{path}\\{version}"
                            })
                            
                        except FileNotFoundError:
                            pass
                        
                        i += 1
                    except OSError:
                        break
                        
        except FileNotFoundError:
            continue
    
    return {
        'current_python': sys.executable,
        'registry_installations': python_installations,
        'total_found': len(python_installations)
    }

# Detect from registry
registry_info = detect_python_from_registry()

if 'error' in registry_info:
    print(f"Error: {registry_info['error']}")
else:
    print(f"Current Python: {registry_info['current_python']}")
    print(f"\nPython installations found in registry: {registry_info['total_found']}")
    
    for install in registry_info['registry_installations']:
        print(f"\nVersion: {install['version']}")
        print(f"  Path: {install['path']}")
        print(f"  Registry: {install['hive']} - {install['registry_path']}")

Quick Windows Python Summary Script #

One comprehensive script to get all essential information:

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Usage Tips #

When to use these scripts:

  • Setting up new Windows development environments
  • Troubleshooting Python installation issues
  • Documenting system configurations
  • Switching between multiple Python installations

Best practices:

  • Save these scripts for quick environment checking
  • Use in deployment scripts to verify environments
  • Include in project setup documentation
  • Test across different Windows Python installations

These scripts help you quickly identify and verify which Python installation you're working with on Windows systems.

Related Snippets

Snippet Beginner

Python Scripts to Detect Which Version You're Running

Ready-to-use Python code snippets to check which Python version you're using, with detailed version information and compatibility checks.

#python #version #detection +2
View Code
Installation
Snippet Beginner

Python Windows Detection Scripts - Which Python Utilities

Ready-to-use Python scripts to detect which Python installation you're using on Windows systems with version and path information.

#python #windows #detection +2
View Code
Installation
Snippet Beginner

Python Version Checking Code Examples and Scripts

Ready-to-use Python code snippets to check what Python version do I have programmatically with different output formats.

#python #version #code-snippet +2
View Code
Installation
Snippet Beginner

Python Code to Fix Import Error Module Not Found Despite Installation

Ready-to-use Python scripts and functions to diagnose and fix import errors when modules are installed but not found.

#python #import #error +2
View Code
Installation