Tuesday, May 28, 2024

Controlling Home windows with Python — SitePoint

Must read


On this fast tip, excerpted from Helpful Python, Stuart appears to be like at methods to manage the Home windows OS with Python.

The Home windows Registry

Home windows is totally controllable from code utilizing the Win32 API, and Microsoft gives intensive documentation at Microsoft Docs for the whole lot that Home windows can programmatically do. All of that is accessible from Python as effectively, though it could actually appear somewhat impenetrable if we’re not already accustomed to the Win32 API’s explicit means of working. Thankfully, there are numerous wrappers for these low-level APIs to make code simpler to put in writing for Python programmers.

A easy instance is to work together with the Home windows Registry. Python truly consists of the winreg module for doing this out of the field, so no additional set up is required. For an instance, let’s verify the place the Program Information folder truly lives:

>>> import winreg
>>> hive = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
>>> key = winreg.OpenKey(hive, r"SOFTWAREMicrosoftWindowsCurrentVersion")
>>> worth, sort = winreg.QueryValueEx(key, "ProgramFilesDir")
>>> worth
'C:Program Information'

Uncooked Strings

Within the code above, we’re utilizing “uncooked strings” to specify the important thing title:

r"SOFTWAREMicrosoftWindowsCurrentVersion"

Strings handed to the Win32 API usually embrace the backslash character (), as a result of Home windows makes use of it in file paths and registry paths to divide one listing from the subsequent.

Nonetheless, Python makes use of a backslash as an escape character to permit including particular, untypeable characters to a string. For instance, the Python string "first linensecond line" is a string with a newline character in it, in order that the textual content is unfold over two strains. This could battle with the Home windows path character: a file path equivalent to "C:newdirmyfile.txt" would have the n interpreted as a newline.

Uncooked strings avert this: prefixing a Python string with r removes the particular that means of a backslash, in order that r"C:newdirmyfile.txt" is interpreted as supposed. We are able to see that backslashes are handled specifically by the worth we get again for the folder location: it’s printed as 'C:Program Information'—with the backslash doubled to take away its particular that means—however that is how Python prints it fairly than the precise worth. Python may have printed that as r'C:Program Information' as an alternative.

The Home windows API

Studying the registry (and much more so, writing to it) is the supply of a thousand hacks on internet pages (a lot of that are previous, shouldn’t be linked to, and use the traditional REGEDT32.EXE), however it’s higher to really use the API for this. (Raymond Chen has written many lengthy unhappy tales about why we should always use the API and never the registry.) How would we use the Win32 API from Python to work this out?

The Win32 Python API is accessible within the PyWin32 module, which might be obtained with python -m pip set up pywin32. The documentation for the module is fairly sparse, however the core concept is that many of the Home windows Shell API (that’s involved with how the Home windows OS is ready up) is accessible within the win32com.shell package deal. To seek out out the situation of the Program Information folder, MSDN exhibits that we want the SHGetKnownFolderPath operate, to which is handed a KNOWNFOLDERID fixed and a flag set to 0. Shell constants can be found to Python in win32com.shell.shellcon (for “shell constants”), which signifies that discovering the Program Information folder requires only one (admittedly advanced) line:

>>> from win32com.shell import shell, shellcon
>>> shell.SHGetKnownFolderPath(shellcon.FOLDERID_ProgramFiles, 0)
"C:Program Information"

Digging round within the depths of the Win32 API offers us entry to something we might need to entry in Home windows (together with home windows!), however as we’ve seen, it may be fairly sophisticated to learn the way to do what we have to, after which to translate that want into Python. Thankfully, there are wrapper libraries for lots of the capabilities generally used. One good instance is PyGetWindow, which permits us to enumerate and management on-screen home windows. (It claims to be cross-platform, however it truly solely works on Home windows. However that’s all we want right here.)

We are able to set up PyGetWindow with python -m pip set up pygetwindow, after which listing all of the home windows on display and manipulate them:

>>> import pygetwindow as gw
>>> allMSEdgeWindows = gw.getWindowsWithTitle("edge")
>>> allMSEdgeWindows
[Win32Window(hWnd=197414), Win32Window(hWnd=524986)]
>>> allMSEdgeWindows[0].title
'pywin32 · PyPI - Microsoft Edge'
>>> allMSEdgeWindows[1].title
'Welcome to Python.org - Microsoft Edge'

These home windows might be managed. A window object might be minimized and restored, or resized and moved across the display, and centered and delivered to the entrance:

>>> pythonEdgeWindow = allMSEdgeWindows[1]
>>> pythonEdgeWindow.reduce()
>>> pythonEdgeWindow.restore()
>>> pythonEdgeWindow.measurement
Measurement(width=1050, peak=708)
>>> pythonEdgeWindow.topleft
Level(x=218, y=5)
>>> pythonEdgeWindow.resizeTo(800, 600)

It’s all the time value trying on PyPI for wrapper modules that present a extra handy API for no matter we’re attempting to do with home windows or with Home windows. But when want be, we have now entry to the entire Win32 API from Python, and that can allow us to do something we will consider.

This text is excerpted from Helpful Python, out there on SitePoint Premium and from book retailers.





Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article