Frequently I need to launch sub processes from Python. Sometimes these processes don’t work as expected, and end up blocking the program. If you want to launch a command from python, and cut it off after a certain amount of time, I recommend the threading module.
Here is how to limit the command to running for roughly 5 seconds:
#!/usr/bin/env python
import commands
import datetime
import time
import threading
class runCommand(threading.Thread):
def run(self):
status, output = commands.getstatusoutput('sleep 8')
if __name__ == "__main__":
startTime = datetime.datetime.now()
maximumRunTime = datetime.timedelta(seconds = 5)
mythread = runCommand()
mythread.start()
while 1:
if mythread.isAlive():
print "Thread has not returned yet..."
else:
print "Thread is all done."
break
if (datetime.datetime.now() - startTime) > maximumRunTime:
print "Thread has ran too long, giving up."
break
time.sleep(1)
print "Program done"
So when we enter main, I assign the current time to startTime. Then I define maximumRunTime as a difference of 5 seconds. The thread is started, and every second we check to see if it is still running. If it is, we go ahead and check how much real time has elapsed.
Related posts:
- Python Commands Module Python Commands Module The Python module ‘commands’ allows commands to...
- Python and real time graphical analysis I have a camera which has a motor attached which...
- Cherokee / Django tip: Timeout value The default Cherokee timeout value is 15 seconds. I write...
- Python-RPM If you ever get to use this library, it’s design...
- Creating graphs in python Slow Friday today, so was digging through my $HOME and...
#1 by Ning on June 19, 2009 - 9:53 am
Quote
what about thread.Event and then set a timeout on wait()?
#2 by prayer1 on July 18, 2009 - 8:33 am
Quote
and what about the join method for Threads?