pywin32 (Python for Windows Extensions)
pywin32 is an open-source Python library that provides extensive access to many Windows APIs and the Component Object Model (COM). It enables Python scripts to automate Windows applications like Excel and Outlook, interact with system services, manage the clipboard, and perform various other Windows-specific operations. The current version is 311, and the project maintains a frequent release cadence, offering incremental improvements and bug fixes.
Warnings
- breaking Binary .exe installers for pywin32 have been deprecated since build 306. Installation should now be performed using pip.
- gotcha The `pywin32_postinstall.py` script (located in your Python Scripts directory) is crucial for some functionalities, especially for global installations or when running Windows services, but it should generally NOT be run inside virtual environments. It may require elevated administrator privileges.
- gotcha It is critical to match the 'bittedness' (32-bit or 64-bit) of `pywin32` with your Python interpreter's architecture. Installing a 64-bit `pywin32` with a 32-bit Python (or vice-versa) will lead to `ImportError: DLL load failed` or similar issues.
- gotcha `pywin32` can be challenging to use in embedded Python environments due to how it handles DLL loading, which may cause import failures.
- gotcha Documentation for `pywin32` is often reported by users as being sparse or outdated, especially for less common functionalities. Adapting VBA examples for COM automation often requires trial and error.
- gotcha When running Python scripts as Windows services using `pywin32`, ensure that the Python installation and required DLLs are accessible to the user account under which the service runs (e.g., LocalSystem). Permissions issues can prevent services from starting or functioning correctly.
Install
-
pip install pywin32 --upgrade
Imports
- win32com.client
import win32com.client
- win32api
import win32api
- win32serviceutil
import win32serviceutil
- win32clipboard
import win32clipboard
Quickstart
import win32com.client
import os
try:
# Try to get an active Excel instance, or create a new one
excel = win32com.client.GetActiveObject("Excel.Application")
except Exception: # pythoncom.com_error if pywin32 is installed correctly
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True # Make Excel visible
workbook = excel.Workbooks.Add() # Add a new workbook
sheet = workbook.Sheets(1) # Get the first sheet
sheet.Cells(1, 1).Value = "Hello from pywin32!"
sheet.Cells(2, 1).Value = "Automating Windows with Python."
print("Excel opened and data written. Please check your Excel application.")
print("You might need to close Excel manually after inspection.")