Pywin32

https://github.com/mhammond/pywin32

pywin32:Its core value is enabling developers to easily achieve in-depth interaction between Python and the Windows system, covering scenarios from...

Python Pywin32

Have you encountered similar requirements when developing Windows applications or automation tasks?

Need: After packaging your developed application into an EXE file, make it run automatically on the computer, and determine if the application is running normally by monitoring system processes.

Need: Want to secondary-develop tools installed on the operating system, retrieve OS resources, and interact with applications.

Today, I recommend a practical tool — pywin32. This library has been downloaded over 100 million times on GitHub and is known as a “must-have utility” for Python on the Windows platform.

What is pywin32?

pywin32 is a third-party library specifically developed for Python, first released by Mark Hammond in 1998. It provides robust support for Python to call Windows APIs and is hailed as an “indispensable tool” for Python on the Windows platform.

Its core value is enabling developers to easily achieve in-depth interaction between Python and the Windows system, covering scenarios from basic system operations to complex desktop application control.

Address: https://github.com/mhammond/pywin32

How Powerful is pywin32?

Specifically, the pywin32 library includes multiple functional modules:

win32api module: Directly access common Windows API functions (e.g., MessageBox to display message boxes, retrieve system metrics, etc.).

win32gui module: Manipulate graphical user interfaces (e.g., FindWindow to locate window handles, SetWindowPos to adjust window positions).

win32con module: Define common constants and macros (e.g., MB_OK for “OK” button, HWND_TOPMOST for always-on-top windows).

win32process module: Manage processes (e.g., CreateProcess to create new processes, TerminateProcess to end processes).

win32security module: Handle security operations (e.g., permission adjustments, security descriptor processing).

Developers can complete system-level operations using Python syntax without deep knowledge of the Win32 SDK — it’s convenient and efficient.

Installing pywin32 Dependencies

Press the Win + R shortcut to open the Run dialog, enter cmd and press Enter to launch the command-line terminal, then run the following command to install:

pip install pywin32

Function Examples — Just the Tip of the Iceberg

Example ①: Automatically Retrieve User Hardware Information

python

# Get computer name/OS version
computer_name = win32api.GetComputerName()
os_version = win32api.GetVersion()  

# Execute shutdown (shuts down after 30 seconds)
win32api.ExitWindowsEx(win32api.EWX_SHUTDOWN | win32api.EWX_FORCE, 30)

Example ②: Background File Copy/Deletion

python

# Copy file
win32api.CopyFile(src_file, dst_file)

# Delete file
win32api.DeleteFile(fileName)

Example ③: Manipulate Mouse Clicks

python

# Get mouse position
win32api.GetCursorPos()

# Move mouse pointer to (x, y) on screen
win32api.SetCursorPos((x, y))

# Simulate left mouse button press
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)

# Restrict mouse cursor movement range
win32api.ClipCursor(rect)

Example ④: Make the OS Play a Specific Sound

python

# Play a beep (frequency: tone frequency, duration: sound length in milliseconds)
win32api.Beep(frequency, duration)

win32api.Beep(440, 5000)  # Play 440Hz beep for 5 seconds

Example ⑤: Automate Software Login

Suppose you need to auto-login to software with a login window titled “Login”. Use pywin32 to find the window and send the username/password:

python

def auto_login():
    hwnd = win32gui.FindWindow(None, "Login")
    if hwnd:
        # Send username (replace with target input control hwnd if needed)
        win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, None, "username")
        # Send password (replace with target input control hwnd if needed)
        win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, None, "password")
        # Click "OK" button
        win32gui.SendMessage(hwnd, win32con.WM_COMMAND, win32con.IDOK, None)

Example ⑥: Clean Disk Files to Free Up Space

Programs often generate large amounts of temporary files that take up disk space. Use pywin32 to write a script for regular cleanup:

python

import os

def clean_temp_files():
    temp_dir = os.environ.get("TEMP")
    for file_name in os.listdir(temp_dir):
        file_path = os.path.join(temp_dir, file_name)
        if os.path.isfile(file_path):
            try:
                os.remove(file_path)  # Skip locked files with try-except
            except PermissionError:
                pass

Example ⑦: Auto Start/Stop/Monitor Program Processes

Monitor if a target application process is running normally:

python

def is_process_running(process_name):
    for pid in win32process.EnumProcesses():
        try:
            handle = win32api.OpenProcess(
                win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ,
                False, 
                pid
            )
            if handle:
                exe_path = win32process.GetModuleFileNameEx(handle, 0)
                if process_name.lower() in exe_path.lower():
                    win32api.CloseHandle(handle)
                    return True
                win32api.CloseHandle(handle)
        except (PermissionError, ValueError):
            continue  # Skip processes without access
    return False

Example ⑧: Custom Game Auto-Clicker (Like a Macro Tool)

Need to repeatedly click a position while gaming? Use pywin32 to implement auto-click — just like a game macro!

python

import time

def auto_clicker(x, y, clicks=100, interval=0.1):
    """Auto-clicker: simulate mouse clicks at a specified position"""
    for i in range(clicks):
        win32api.SetCursorPos((x, y))  # Move mouse to target position
        # Press left mouse button
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
        # Release left mouse button
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
        time.sleep(interval)  # Click interval
        print(f"Auto-clicked {i+1} times")

# Usage: Auto-click 50 times at (500, 300) with 0.2s interval
auto_clicker(500, 300, clicks=50, interval=0.2)

Notes for Use

  1. Compatibility: pywin32 only supports Windows — it does not work on Linux or macOS.

  2. Permissions: If you encounter permission issues, try running the Python script as an administrator.

  3. Error Handling: Errors may occur when calling Windows APIs — it is recommended to add error-handling logic to your code.

nothing