pywin32 python library for Windows OS

  • pywin32 is an open source python library that can be used to access Windows COM. Access to COM means that we can control and modify windows programs using python.
    This helps us to implement almost any thing a windows program can do, like working with excel data, sending outlook email, track session lock/unlock events, mouse pointer data, screen information, etc.

    pywin32 is a huge library and forms the foundation of many other libraries.
    For example, any python GUI libraries that supports Windows OS implements pywin32, as this already has components related to windows GUI.

    This article lists some of the most important modules of pywin32 with sample usages.
    Complete documentation here.

  1. Install pywin32

    Download and install the latest version of python from Python Website.

    Set up virtual environment also if needed.

    Install pywin32 using the command: pip install pywin32

  2. To check if pywin32 installed successfully

    Type command pip freeze
    Should give an output like:

    pywin32==302
    
  3. Important pywin32 modules

    pywin32 has many sub modules, which handles specific functions. When working with pywin32 in our python code, we will be importing these modules mostly, rather than importing pywin32. Below are list of some of the most used modules and its functionalities.

    Module Name Description
    win32 clipboard Access and modify clipboard data.
    win32api Enables implementing functions like shutdown or restart, log off, beep from speaker, copy file, delete file, search file get computer name, current user name, local time, windows OS details etc.
    odbc To manage an odbc connection
    timer Start a timer to execute a function. Stop timer.
    win32evtlog Actions like retrieving and reading through a list of events, clearing event logs, backing it up, etc
    win32file Create directories, create/copy/ move/delete files, get/set filename, get file size, read/write strings to file, etc
    win32gui Working with windows GUI like, creating and modifying a GUI window, dialog boxes, writing text to window, creating images in window, draw shapes like, ellipse, rectangle, polygons, lines, etc
    win32ts Actions like, listing all the sessions in a server, get information about a session, logging off a session, etc
    pywintypes Create GUID, time object etc.
  4. win32clipboard samples

    Helps to work with clipboard data.

    import win32clipboard as w
    print("Number of formats currently on clipboard : ", w.CountClipboardFormats())#'Should have some copied data before executing this line'
    w.OpenClipboard(None)
    str = w.GetClipboardData(1)
    print("Clipboard data : ", str)
    w.SetClipboardText("New data in clipboard", 1)
    str = w.GetClipboardData(1)
    print("New clipboard data : ", str)
    print("Empty clipboard : ", w.EmptyClipboard())
    #str = w.GetClipboardData(1)#'Will throw an error because clipboard emptied - Specified clipboard format is not available.'
    
  5. win32api samples

    Enables implementing functions like shutdown or restart, log off, beep from speaker, copy file, delete file, search file get computer name, current user name, local time, windows os details etc.

    import win32api as w
    str = w.Beep(100, 1000)#'Frequency and duration in ms'
    w.CopyFile('src_file_name', 'dest_file_name', 0)#'Provide right path for it to work'
    w.DeleteFile('file_name')
    w.ExitWindows(0, 0)#'Log off current user'
    w.FindFiles('srchkey')#'Keyword should be a file or directory name. Wild cards * and ? allowed'
    w.FindExecutable(filename, dir)#'Retrieves details of exe associated with file specified'
    w.GetUserName()#'Current user name'
    w.GetLocalTime()
    w.GetSystemInfo()
    w.GetTickCount()#'Milliseconds since start of the system'
    w.mouse_event(0, 10, 200, 0, 0)#'Simulate mouse event'
    
  6. odbc Samples

    To list out all the ODBC data sources available, use below code. Will return None, if nothing is available.

    import odbc
    print(odbc.SQLDataSources(1))
    
  7. timer samples

    Start a timer to execute a function. Stop timer.

    import timer as t
    
    def func(timer_id, time):
        print('Timer function called every second')
        t.kill_timer(id)
    
    id = t.set_timer(1, func)
    print(id)
    
  8. win32evtlog samples

    Read through windows event logs of the specified server, clear it, backup, etc.

    import win32evtlog as w
    
    hdle = w.OpenEventLog(None,'Information')#'Server name and log name'
    flags = w.EVENTLOG_SEQUENTIAL_READ | w.EVENTLOG_BACKWARDS_READ
    ev=w.ReadEventLog(hdle,flags,0)
    print (ev)
    ev=w.CloseEventLog(hdle)
    
  9. win32file samples

    Create directories, create/copy/move/delete files, get/set filename, get file size, read/write strings to file, etc.

    import win32file as w
    
    w.CreateDirectory('New Dir', None)
    hdle = w.CreateFile('NewFile.txt', w.GENERIC_READ, 0, None, w.CREATE_NEW, 0, None)
    print(w.GetFileSize(hdle))
    print(w.ReadFile(hdle, 1000, None))
    #w.WriteFile(hdle, 'New Text', None)#'While creating file use w.GENERIC_WRITE for this to work'
    hdle.close()
    w.DeleteFile('NewFile.txt')
    
  10. win32gui samples

    Working with windows GUI like, creating and modifying a GUI window, dialog boxes, writing text to window, creating images in window, draw shapes like, ellipse, rectangle, polygons, lines, etc. This is a big topic. Below example just shows creating a window with a specified size.

    import win32api as api
    import win32con as con
    import win32gui as gui
    import win32ts as ts
    
    cname = "Test"
    hndle = api.GetModuleHandle(None)
    wc = gui.WNDCLASS()
    wc.hInstance = hndle
    wc.lpszClassName = cname
    cl = gui.RegisterClass(wc)
    s = con.WS_OVERLAPPEDWINDOW
    w = gui.CreateWindow(cl, cname, s, 100, 100, 500, 500, 0, 0, hndle, None)
    gui.UpdateWindow(w)
    gui.ShowWindow(w, con.SW_SHOW)
    ts.WTSRegisterSessionNotification(w, ts.NOTIFY_FOR_ALL_SESSIONS)
    
    if __name__ == '__main__':
        gui.PumpMessages()
    
  11. win32ts

    Actions like, listing all the sessions in a server, get information about a session, logging off a session, etc.
    Refer sample application Sedentary Reminder for usage details.

  12. pywintypes samples

    Create GUID, time object etc.

    import pywintypes
    print("New GUID : ", pywintypes.CreateGuid())
    print("Check Unicode : ", pywintypes.IsTextUnicode("1", 1))#Result is non zero if test passes
    print("New Time : ", pywintypes.Time(1000000000))
    
Absolute Code Works - Python Topics