Welcome, guest | Sign In | My Account | Store | Cart

various Windows Script Host (WSH) examples converted to Python. The originals are at: http://msdn.microsoft.com/scripting/default.htm?/scripting/windowshost/doc/wsMthRun.htm http://msdn.microsoft.com/scripting/windowshost/doc/wsproenvironment.htm http://msdn.microsoft.com/scripting/default.htm?/scripting/windowshost/doc/wsMthSendKeys.htm

Note that this script is a Python program that utilizes WSH, so use a .py extension rather than .pys.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import sys
import win32api
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
# launch Notepad to edit this script, simple version
# sys.argv[0] is WScript.ScriptFullName in WSH
#shell.Run("notepad " + sys.argv[0])

# this time set the window type, wait for Notepad to be shut down by the user,
# and save the error code returned from Notepad when it is shut down
# before proceeding
ret = shell.Run("notepad " + sys.argv[0], 1, 1)
print ret

# open a command window, change to the path to C:\ ,
# and execute the DIR command
shell.Run("cmd /K CD C:\ & Dir")

# environment strings
print shell.ExpandEnvironmentStrings("%windir%")

It is possible to use the functionality of WSH such as SendKeys and ExpandEnvironmentStrings from within a regular Python program further enhancing the use of Python for system administration and automating tasks in a Windows environment.

3 comments

Peter Bengtsson 20 years, 6 months ago  # | flag

why? And what is this script good for?

Please provide examples of how it can be used. I'd love to be able to right click a .py file and open it in IDLE. Can that be done with COM?

Jason Miller 20 years, 4 months ago  # | flag

Am I missing something? Perhaps I'm missing something, but coming from a VB background, we were taught (frequently, often and painfully) that if you didn't explicitly kill your COM objects when you were done with them then you were probably going to be opening memory holes. I would expect that this also holds true of Python (when done with a COM object, close the fool thing), but I can't find any examples... inclusive of this one.

Alex Martelli 20 years, 1 month ago  # | flag

not a big worry. Python (and VB) do garbage collection, so will eventually close your COM objects when you're done with them (Python is better at it -- no worry even if you have a cycle of references -- but it's not a worry all that big in VB either, as you rarely make cycles, and it goes away in VB.NET anyway as it gains full GC like Python).