- pywin32 python library for Windows OS
- Contents
- Install pywin32
- To check if pywin32 installed successfully
- Important pywin32 modules
- win32clipboard samples
- win32api samples
- odbc Samples
- timer samples
- win32evtlog samples
- win32file samples
- win32gui samples
- win32ts
- pywintypes samples
- pywin32
- Docs
- Support
- Binaries
- Installing via PIP
- The specified procedure could not be found / Entry-point not found Errors?
- Running as a Windows Service
- Building from source
- Release process
- win32api¶
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.
Contents
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
To check if pywin32 installed successfully
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. |
win32clipboard samples
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.'
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'
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))
timer samples
import timer as t def func(timer_id, time): print('Timer function called every second') t.kill_timer(id) func) print(id)
win32evtlog samples
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)
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')
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()
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.
pywintypes samples
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))
- Compress/Resize Images Online
- Sample Tools
- FD Calculator
- RD Calculator
- Sedentary Reminder
- Answer Sheet Validator
- Excel Ranking Tool
- Tutorials
- Tkinter
- Kivy
- KV Language
- Flask Web Framework
- Django Web Framework
- pywin32 Windows API
- python-docx Word
- openpyxl Excel
- pyodbc SQL Server
- cx_Oracle Oracle
- pymysql MySQL
- psycopg2 PostgreSQL
- Web Apps
- Flask CRUD with JSON
- Flask CRUD with SQL Server
- Flask CRUD with Oracle
- Flask CRUD with MySQL
- Flask CRUD with PostgreSQL
- Flask CRUD with MongoDB
- Django CRUD with JSON
- Django CRUD with SQL Server
- Django CRUD with Oracle
- Django CRUD with MySQL
- Django CRUD with PostgreSQL
- Django CRUD with MongoDB
- Simple Games
- Pong Game using Tkinter
- Shooting Game using Kivy
- More Python Topics
pywin32
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.
Only Python 3 is supported. If you want Python 2 support, you want build 228 .
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
Installing via PIP
You should install pywin32 via pip — eg,
python -m pip install —upgrade pywin32
If you encounter any problems when upgrading (eg, «module not found» errors or similar), you should execute:
python Scripts/pywin32_postinstall.py -install
This will make some small attempts to cleanup older conflicting installs.
Note that if you want to use pywin32 for «system wide» features, such as registering COM objects or implementing Windows Services, then you must run that command from an elevated (ie, «Run as Administrator) command prompt.
For unreleased changes, you can download builds made by github actions — choose any «workflow» from the main branch and download its «artifacts»)
The specified procedure could not be found / Entry-point not found Errors?
A very common report is that people install pywin32, but many imports fail with errors similar to the above.
In almost all cases, this tends to mean 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 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»)
Running as a Windows Service
Modern Python installers do not, by default, install Python in a way that is suitable for running as a service, particularly for other users.
- 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 .
- Manually copy pythonservice.exe from the site-packages/win32 directory to the same place as these DLLs.
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:
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, commit it.
- Update setup.py with the new build number.
- Execute build.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
win32api¶
Get a handle that can be used by the UpdateResource() .
result (hModule) – Handle of the resource.
End the update resource of the handle.
- handle (hModule) – The handle of the resource as it is returned by BeginUpdateResource()
- discard (bool) – When True all writes are discarded.
List languages of a resource module.
resource_languages (list) – List of the resource language ids.
Enumerates all the resources of the specified type within a module.
resource_names (list) – The list of resource names (unicode strings) of the specific resource type in the module.
Enumerates resource types within a module.
Parameters: | hModule (handle) – The handle to the module. |
---|---|
Returns: | resource_types (list) – The list of resource types in the module. |
win32ctypes.pywin32.win32api. FreeLibrary ( hModule ) [source] ¶
Free the loaded dynamic-link library (DLL) module.
If necessary, decrements its reference count.
Parameters: | handle (hModule) – The handle to the library as returned by the LoadLibrary function. |
---|
win32ctypes.pywin32.win32api. GetSystemDirectory ( ) [source] ¶
Returns: | result (str) – The path to the System directory. |
---|
win32ctypes.pywin32.win32api. GetTickCount ( ) [source] ¶
The number of milliseconds that have elapsed since startup
Returns: | counts (int) – The millisecond counts since system startup. |
---|
win32ctypes.pywin32.win32api. GetWindowsDirectory ( ) [source] ¶
Get the Windows directory.
Returns: | result (str) – The path to the Windows directory. |
---|
win32ctypes.pywin32.win32api. LoadLibraryEx ( fileName, handle, flags ) [source] ¶
Loads the specified DLL, and returns the handle.
handle (hModule) – The handle of the loaded module
Find and Load a resource component.
resource (bytes) – The byte string blob of the resource
Note PyWin32 version 219, on Python 2.7, can handle unicode inputs. However, the data are stored as bytes and it is not really possible to convert the information back into the original unicode string. To be consistent with the Python 3 behaviour of PyWin32, we raise an error if the input cannot be converted to bytes .