Easy Automation on Windows Using Python’s pywin32 Library

paz 22/12/2025

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.

๐Ÿ Conclusion

As a powerful tool, the pywin32 library has many more application scenarios for automation tasks, system resource management, window operations, and beyond!