Working with Windows Scripting Host (WSH) from Python
Credit: Kevin Altis
Problem
You need to use the Windows Scripting Host (WSH) to perform the same tasks as in the classic WSH examples, but you must do so by driving the WSH from within a normal Python script.
Solution
Python’s abilities on Windows are greatly enhanced
by win32all’s ability to access
COM automation servers, such as the WSH. First, we connect to the
Windows shell’s COM automation interface:
import sys, win32com.client
shell = win32com.client.Dispatch("WScript.Shell")Then, we launch Notepad to edit this script in the simplest way
(basically, with the same functionality as
os.system). This script’s name
is, of course, sys.argv[0], since
we’re driving from Python:
shell.Run("notepad " + sys.argv[0])For a .pys script driven from WSH, it would be
WScript.ScriptFullName instead.
shell.Run has greater functionality than the more
portable os.system. To show it off, we can set the
window type, wait until Notepad is shut down by the user, and get the
code returned from Notepad when it is shut down before proceeding:
ret = shell.Run("notepad " + sys.argv[0], 1, 1)
print "Notepad return code:", retNow, we open a command window, change the path to
C:\, and execute a dir:
shell.Run("cmd /K CD C:\ & Dir")Note that cmd works only on Windows NT/2000/XP; on
Windows 98/ME, you need to run Command instead,
and this does not support the & joiner to
execute two consecutive commands. The shell object
has many more methods besides the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access