Better Process Control: The win32api Module

The module win32api provides some additional techniques for manipulating processes. These allow you to perform many of the common requirements for starting new processes, but still don’t provide the ultimate in low-level control.

win32api.WinExec

The WinExec function behaves similarly to the os.system function, as described previously, but it provides some concessions for GUI programs; namely, no console is created, and the function doesn’t wait until the new process has completed. The function takes two parameters:

  • The command to execute

  • Optionally, the initial state for the application’s window

For example, to execute notepad, using the default window state, you can execute the following code:

>>> import win32api
>>> win32api.WinExec("notepad")
>>>

notepad should appear in a normal window, and Python continues executing commands before you close notepad.

To show notepad maximized:

>>> import win32api, win32con
>>> win32api.WinExec("notepad", win32con.SW_SHOWMAXIMIZED)
>>>

win32api.ShellExecute

The win32api module also provides another useful function for creating new processes. The ShellExecute function is primarily used to open documents, rather than start arbitrary processes. For example, you can tell ShellExecute to “open MyDocument.doc.” Windows itself determines which process to use to open .doc files and start it on your behalf. This is the same function Windows Explorer uses when you click (or double-click) on a .doc file: it calls ...

Get Python Programming On Win32 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.