Python – A Better os.system with Time Out
Thursday, February 16th, 2006(Disclaimer: Only better for me, only for win32)
Here’s the Python function I now use in Windows instead of os.system(inspired by David Stubbs):
import time
import win32process
PROCESS_STILL_RUNNING=259
def system(command_string,seconds_until_time_out):
"""Works like os.system but has timeout and
only for win32"""
pinfo = win32process.CreateProcess(
None, command_string, None, None, 0, 0,
None, None, win32process.STARTUPINFO())
retval = PROCESS_STILL_RUNNING
while retval == PROCESS_STILL_RUNNING:
time.sleep(1)
seconds_until_time_out = seconds_until_time_out - 1
if seconds_until_time_out <= 0:
win32process.TerminateProcess(pinfo[0], 1)
print "ERROR: Process timeout"
break
retval = win32process.GetExitCodeProcess(pinfo[0])
return retval
You'll need the Win32 Extensions for Python to run it.
Basically what is does is use the Windows process handling abilities of the Python Win32 Extensions to launch your command, monitor the status of that process, and terminate it if need be.
Please post questions and improvements here.
Here are some searches I made before finding/writing this.
- python Exception after timeout
- python os.system hangs
- python os.system bug