Python – How to Actually Use os.spawn in Windows
Update: The subprocess module is the way to go for Python 2.4 and later. It aims to handle all your system calling needs, e.g., os.system, os.spawn*, os.popen*, popen2.*, and commands.*
Here’s my new snippet using subprocess to launch/spawn a process and not wait for it:
from subprocess import Popen Popen([r'C:\Python24\Python.exe','C:\\AUTOMA~1\\AOSWEB\\ACTUAL~1.PY',str(order_no)]) #use win32api.GetShortPathName to get that 'C:\\AUTOMA~1\\AOSWEB\\ACTUAL~1.PY' thing, #Python/Windows aint like spaces ..
Here is my previous method which also seems to work:
Wow, I spent an hour trying to get os.spawn to work in Windows. The documentation does nothing!
Finally I found this thread where Doug Holton has written a nice “wrapper” for os.spawn:
import os
def run (program, *args):
"Run external program, wait til it quits, and return the exit code"
#Actually comment out line below on windows, I get attribute error here
spawn = os.spawnvp #not available on windows though
if os.name == "nt": spawn = os.spawnv
return spawn(os.P_WAIT, program, (program,) + args)
def start (program, *args):
"Start an external program and return immediately, returning proc id"
#Actually comment out line below on windows, I get attribute error here
spawn = os.spawnvp #not available on windows though
if os.name == "nt": spawn = os.spawnv
return spawn(os.P_NOWAIT, program, (program,) + args)
#example:
errcode = run('cp','index.html','index2.html')
if errcode == 0: #no error
pid = start('cp','index2.html','index3.html')
else:
print "error finding or copying the index.html file"
I think Windows commands have always been a sore spot for Python I’m afraid
Of course I would guess the blame lies with Windows like everything else in this world though.
[tags]os.spawn, spawn, popen, windows[/tags]
You should check out the subprocess module… it’s in 2.4 and above, but it works with 2.3 too.
–titus
Hmm, subprocess does look interesting. It says it’s meant to replace os.spawn among others.
I’ll certainly try it out.