这是我的操作方式...它确实使用了子进程,因此您需要对其进行调整以使用popen。
class KillerThread(threading.Thread):
def __init__(self, pid, timeout, event ):
threading.Thread.__init__(self)
self.pid = pid
self.timeout = timeout
self.event = event
self.setDaemon(True)
def run(self):
self.event.wait(self.timeout)
if not self.event.isSet() :
try:
os.kill( self.pid, signal.SIGKILL )
except OSError, e:
#This is raised if the process has already completed
pass
def runTimed(dt, args, kwargs ):
event = threading.Event()
proc = subprocess.Popen(args, **kwargs )
killer = KillerThread(proc.pid, dt, event)
killer.start()
(stdout, stderr) = proc.communicate()
event.set()
return (stdout,stderr, proc.returncode)
#EXAMPLE USAGE - lets it run for at most 3 seconds
(stdout, stderr, returncode) = \
runTimed(3, \
["path/to/my/executable", "arg1" ] , \
{'stdout':subprocess.PIPE, 'stderr':subprocess.PIPE} )
如果使用stderr,stdout,则可以避免使用其他线程
直接使用而不是使用通讯,您只需要小心在这些句柄上使用非阻塞IO。
子进程
– Victor HurdugaciNovember 08, 2009 12:59