Spawning a process in IronPython
I've been using IronPython recently as a scripting language because its string handling and ability to provide structured programming support is so much richer — and accessibly documented — than old .BAT & .CMD file programming supports. The downside is that the old style files make launching sub-processes trivial. So, in the spirit of DRY (Don't Repeat Yourself), here's the file to import.
And yes, this is really another example of how to use .Net rather than how to use Python.
import sys | |
import System | |
from System.Diagnostics import * | |
from System.IO import * | |
#--------------------------------------------------- | |
def spawn(cmd, args, wait=True): | |
"""Spawn a process running executable 'cmd' with the rest of the command line given by | |
'args'. If wait is given as False, the rest of the script keeps on going while the sub-process | |
is running. By default, the script waits for the sub-process to finish before resuming. | |
The usual reminder about DOS built-in commands like 'del' applies -- you have to give cmd='cmd' | |
and args = '/C del ' plus what you would give as an argument to 'del'. | |
""" | |
# Fire off a separate process | |
# Optional embellishments presented as comments | |
proc = Process() | |
start = ProcessStartInfo() | |
start.FileName = cmd | |
start.Arguments = args | |
start.UseShellExecute = 0 # needed to allow redirection | |
start.RedirectStandardOutput = 1 # ask for redirection | |
proc.StartInfo = start | |
# print cmd+" "+args | |
try : | |
proc.Start() | |
if wait: | |
proc.WaitForExit() | |
#line = proc.StandardOutput.ReadToEnd() | |
#print line | |
except: | |
#print "FAILED" | |
pass | |
#--------------------------------------------------- | |
if __name__ == '__main__' : | |
spawn("cmd", "/c type spawn.py") | |
sys32dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) | |
paint = "\""+sys32dir+"\\mspaint.exe\"" | |
spawn(paint, "", False) | |
print "Done - but paint should still be showing" |
1 comment :
Hello Steve.
Thanks for adding your example for the cookbook. By sheer chance I was using the Process class today and added an example before I saw yours.
I've merged your code with mine in the 'launching a sub-process' page, and added a link there.
Thanks
Post a Comment