Pywin32

Introduction

Pros and Cons

Pros

Cons

  • Re-arranged all api functions into several modules and packages.
  • Re-arranged function signatures (parameter specification) of api functions
  • Therefore, You have to refer its documents
  • No access for customized interface

Structures

2-Step implementation

  1. First, implemented two c extensions (pywintypesXX.dll and pythoncomXX.dll)
    • 1. pywintypes
      • for win32 sdk api's
      • re-arrange user32.dll, kernel32.dll, etc.
    • 2. pythoncom
      • for com, oel atl api's
      • re-arrange ole32.dll, oleaut32.dll, etc.
    • these extension modules are located in C:\Python26\Lib\site-packages\pywin32_system32
    • XX is a version number : for example pythoncom26.dll and pywintypes26.dll
  2. Second, create sub-packages upon these extension modules using pyd and py files
    • C:\Python26\Lib\site-packages\win32 (You have to import these packages individually)
    • C:\Python26\Lib\site-packages\win32com
      • C:\Python26\Lib\site-packages\win32com\client
      • C:\Python26\Lib\site-packages\win32com\server
      • C:\Python26\Lib\site-packages\win32com\makegw
    • C:\Python26\Lib\site-packages\win32comext

List of win32 packages

  • You have to import these packages individually

Using Type Library for Early Bounding

makepy.py utility

  • C:\Python26\Lib\site-packages\win32com\client\makepy.py
  • GUI utility
  • parse type library and create python module
    • location: C:\Python26\Lib\site-packages\win32com\gen_py
    • name: typelib id + version number
      • for example, excel COM, creates 00020813-0000-0000-C000-000000000046x0x1x6.py
[
  uuid(00020813-0000-0000-C000-000000000046),
  version(1.6),
]
library Excel
  • module contents
    • IDispatch-based interface class
    • CoClass class
    • enumeration constants

gencache.EnsureModule

  • for programmable parse, use win32com.client.gencache.EnsureModule
  • for example, Excel
>> win32com.client.gencache.EnsureModule("Excel.Application", 1, 6, 0)

win32com.client.gencache.GetModuleForProgID

  • return module for COM
  • for look up the interface, coclass and constants
>> xlLib = win32com.client.gencache.GetModuleForProgID("Excel.Application")
>> print dir(xlLib.constants)
>> print xlLib.NamesToIIDMap.keys()

Getting COM interface and object

Method 1 : Using Dispatch class

Method 2: Using IUnknown or IDispatch interface

Event Processing

EventSink Class

  • method name : OnEventName
    • example: OnNewWorkbook

Method 1: win32com.client.WithEvents

  • event sink object 에서 원래의 object로 갈수 있는 방법이 없으므로 클래스 구현시 proxy 를 이용하여 강제로 집어넣어야 한다

Method 2: win32com.client.DispatchWithEvents

  • event sink object 는 _obj_ 를 이용하여 원래의 object 접근가능