Convert Figma logo to code with AI

mhammond logopywin32

Python for Windows (pywin32) Extensions

5,031
793
5,031
449

Top Related Projects

Windows GUI Automation with Python (based on text properties)

Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers.

4,974

Python for Windows (pywin32) Extensions

Quick Overview

PyWin32 is a Python extension that provides access to many of the Windows APIs from Python. It allows developers to interact with Windows-specific features, services, and components using Python, bridging the gap between Python and Windows system programming.

Pros

  • Extensive coverage of Windows APIs, enabling deep integration with Windows systems
  • Well-maintained and actively developed, with regular updates and bug fixes
  • Provides access to COM objects and Windows services
  • Includes useful tools like PythonWin IDE and Python for Windows Extensions

Cons

  • Windows-specific, limiting cross-platform compatibility
  • Can be complex for beginners due to the vast number of APIs and Windows-specific concepts
  • Documentation can be sparse or outdated for some features
  • Large package size compared to other Python libraries

Code Examples

  1. Accessing the Windows Registry:
import win32api
import win32con

# Read a registry value
key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion")
value, type = win32api.RegQueryValueEx(key, "ProgramFilesDir")
print(f"Program Files directory: {value}")
  1. Creating a Windows service:
import win32serviceutil
import win32service
import win32event

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = "MyPythonService"
    _svc_display_name_ = "My Python Service"

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(MyService)
  1. Interacting with COM objects:
import win32com.client

# Create an instance of Excel
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True

# Create a new workbook and add data
workbook = excel.Workbooks.Add()
sheet = workbook.ActiveSheet
sheet.Cells(1, 1).Value = "Hello"
sheet.Cells(1, 2).Value = "PyWin32"

Getting Started

To get started with PyWin32:

  1. Install PyWin32 using pip:

    pip install pywin32
    
  2. Import the required modules in your Python script:

    import win32api
    import win32con
    import win32com.client
    
  3. Start using PyWin32 functions to interact with Windows APIs:

    # Example: Get system metrics
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
    print(f"Screen resolution: {screen_width}x{screen_height}")
    

Competitor Comparisons

Windows GUI Automation with Python (based on text properties)

Pros of pywinauto

  • Higher-level abstraction for GUI automation
  • Cross-platform support (Windows, Linux, macOS)
  • Built-in support for common UI patterns and controls

Cons of pywinauto

  • Limited access to low-level Windows API functions
  • May have performance overhead for complex automation tasks
  • Smaller community and fewer resources compared to pywin32

Code Comparison

pywinauto example:

from pywinauto.application import Application

app = Application().start("notepad.exe")
app.Notepad.menu_select("File->Exit")
app.Notepad["Don't Save"].click()

pywin32 example:

import win32gui
import win32con

hwnd = win32gui.FindWindow(None, "Untitled - Notepad")
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

pywinauto offers a more intuitive, high-level approach to GUI automation, while pywin32 provides direct access to Windows API functions. pywinauto is better suited for cross-platform automation and simpler tasks, whereas pywin32 is more powerful for Windows-specific development and low-level system interactions.

Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers.

Pros of pythonnet

  • Supports both Windows and Unix-like systems, offering cross-platform compatibility
  • Allows bidirectional interoperability between Python and .NET, enabling Python to consume .NET libraries and vice versa
  • Provides a more seamless integration with .NET, including support for generics and events

Cons of pythonnet

  • May have a steeper learning curve for developers not familiar with .NET concepts
  • Can be slower in some scenarios compared to pywin32 due to the additional layer of abstraction
  • Less mature and potentially less stable than pywin32, which has been around longer

Code Comparison

pywin32:

import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Add()

pythonnet:

import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
from Microsoft.Office.Interop import Excel
excel = Excel.ApplicationClass()
wb = excel.Workbooks.Add()

Both libraries allow interaction with Windows COM objects, but pythonnet uses .NET interop, while pywin32 uses direct COM interaction. pythonnet's approach is more consistent with .NET programming paradigms, while pywin32 is more Python-centric.

4,974

Python for Windows (pywin32) Extensions

Pros of pywin32

  • Extensive documentation and community support
  • Stable and well-maintained project with regular updates
  • Wide range of Windows API functionality covered

Cons of pywin32

  • Large package size due to comprehensive coverage
  • Steeper learning curve for beginners
  • Some features may be outdated or less relevant for modern Windows versions

Code Comparison

Both repositories contain the same codebase, as they are mirrors of the same project. Here's a sample from both:

def GetModuleFileName(hModule):
    """Returns the filename of the module associated with the handle."""
    buf = win32api.PyMakeBuffer(MAX_PATH)
    n = win32api.GetModuleFileName(hModule, buf)
    return buf[:n]

Summary

The comparison between mhammond/pywin32 and mhammond/pywin32 is not applicable, as they are the same repository. pywin32 is a popular Python extension that provides access to many Windows APIs. It offers comprehensive Windows integration for Python developers but may be complex for newcomers. The project is actively maintained and widely used in the Python community for Windows-specific development tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

pywin32

CI PyPI - Version PyPI - Python Version PyPI - Downloads License - PSF-2.0


This is the readme for the Python for Win32 (pywin32) extensions, which provides access to many of the Windows APIs from Python.

See CHANGES.txt for recent notable changes.

Docs

The docs are a long and sad story, but there's now an online version of the helpfile that ships with the installers (thanks @ofek!). Lots of that is very old, but some is auto-generated and current. Would love help untangling the docs!

Support

Feel free to open issues for all bugs (or suspected bugs) in pywin32. pull-requests for all bugs or features are also welcome.

However, please do not open github issues for general support requests, or for problems or questions using the modules in this package - they will be closed. For such issues, please email the python-win32 mailing list - note that you must be subscribed to the list before posting.

Binaries

Binary releases are deprecated. While they are still provided, find them here

Installing via PIP

You should install pywin32 via pip - eg,

python -m pip install --upgrade pywin32

There is a post-install script (see below) which should not be run inside virtual environments; it should only be run in "global" installs.

For unreleased changes, you can download builds made by github actions - choose any "workflow" from the main branch and download its "artifacts")

Installing globally

Outside of a virtual environment you might want to install COM objects, services, etc. You can do this by executing:

python Scripts/pywin32_postinstall.py -install

From the root of your Python installation.

If you do this with normal permissions it will be global for your user (a few files will be copied to the root of your Python install and some changes made to HKCU). If you execute this from an elevated process, it will be global for the machine (files will be copied to System32, HKLM will be changed, etc)

Running as a Windows Service

To run as a service, you probably want to install pywin32 globally from an elevated command prompt - see above.

You also need to ensure Python is installed in a location where the user running the service has access to the installation and is able to load pywintypesXX.dll and pythonXX.dll. In particular, the LocalSystem account typically will not have access to your local %USER% directory structure.

Troubleshooting

If you encounter any problems when upgrading like the following:

The specified procedure could not be found
Entry-point not found

It usually means one of 2 things:

  • You've upgraded an install where the post-install script has previously run. So you should run it again:

    python Scripts/pywin32_postinstall.py -install
    

    This will make some small attempts to cleanup older conflicting installs.

  • There are other pywin32 DLLs installed in your system, but in a different location than the new ones. This sometimes happens in environments that come with pywin32 pre-shipped (eg, anaconda?).

    The possible solutions here are:

    • Run the "post_install" script documented above.
    • Otherwise, find and remove all other copies of pywintypesXX.dll and pythoncomXX.dll (where XX is the Python version - eg, "39")

Building from source

Install Visual Studio 2019 (later probably works, but options might be different), select "Desktop Development with C++", then the following options:

  • Windows 10 SDK (latest offered I guess? At time of writing, 10.0.18362)
  • "C++ for MFC for ..."
  • ARM build tools if necessary.

(the free compilers probably work too, but haven't been tested - let me know your experiences!)

setup.py is a standard distutils build script, so you probably want:

python setup.py install

or

python setup.py --help

Some modules need obscure SDKs to build - setup.py should succeed, gracefully telling you why it failed to build them - if the build actually fails with your configuration, please open an issue.

Release process

The following steps are performed when making a new release - this is mainly to form a checklist so @mhammond doesn't forget what to do :)

  • Ensure CHANGES.txt has everything worth noting. Update the header to reflect the about-to-be released build and date, commit it.

  • Update setup.py with the new build number.

  • Execute make.bat, wait forever, test the artifacts.

  • Upload .whl artifacts to pypi - we do this before pushing the tag because they might be rejected for an invalid README.md. Done via py -3.? -m twine upload dist/*XXX*.whl.

  • Commit setup.py (so the new build number is in the repo), create a new git tag

  • Upload the .exe installers to github.

  • Update setup.py with the new build number + ".1" (eg, 123.1), to ensure future test builds aren't mistaken for the real release.

  • Make sure everything is pushed to github, including the tag (ie, git push --tags)

  • Send mail to python-win32