2014-04-25 44 views

回答

1

你可以安裝subprocess32 modulementioned by @gps - 在subprocess模塊在Python 3.2/3.3的反向移植對2.x的使用它適用於Python 2.7,它包含來自Python 3.3的超時支持。

subprocess.call() is just Popen().wait(),因此在timeout秒中斷一個長期運行的進程:

#!/usr/bin/env python 
import time 
from subprocess import Popen 

p = Popen(*call_args) 
time.sleep(timeout) 
try: 
    p.kill() 
except OSError: 
    pass # ignore 
p.wait() 

如果子過程可以結束越早則便攜式解決方案是use Timer() as suggested in @sussudio's answer

#!/usr/bin/env python 
from subprocess import Popen 
from threading import Timer 

def kill(p): 
    try: 
     p.kill() 
    except OSError: 
     pass # ignore 

p = Popen(*call_args) 
t = Timer(timeout, kill, [p]) 
t.start() 
p.wait() 
t.cancel() 

在Unix上,你可以use SIGALRM as suggested in @Alex Martelli's answer

#!/usr/bin/env python 
import signal 
from subprocess import Popen 

class Alarm(Exception): 
    pass 

def alarm_handler(signum, frame): 
    raise Alarm 

signal.signal(signal.SIGALRM, alarm_handler) 


p = Popen(*call_args) 
signal.alarm(timeout) # raise Alarm in 5 minutes 
try: 
    p.wait() 
    signal.alarm(0) # reset the alarm 
except Alarm: 
    p.kill() 
    p.wait() 

爲了避免在這裏使用線程和信號,Python 3上的subprocess模塊使用busy loop with waitpid(WNOHANG) calls on Unixwinapi.WaitForSingleObject() on Windows

4

我總是用2.7來實現超時的一個簡單方法是利用subprocess.poll()以及time.sleep()延遲。這裏是一個非常簡單的例子:

import subprocess 
import time 

x = #some amount of seconds 
delay = 1.0 
timeout = int(x/delay) 

args = #a string or array of arguments 
task = subprocess.Popen(args) 

#while the process is still executing and we haven't timed-out yet 
while task.poll() is None and timeout > 0: 
    #do other things too if necessary e.g. print, check resources, etc. 
    time.sleep(delay) 
    timeout -= delay 

如果設置x = 600,那麼您的超時時間將達到10分鐘。而task.poll()將查詢過程是否已終止。在這種情況下,time.sleep(delay)將休眠1秒,然後將超時遞減1秒。你可以隨心所欲地玩弄這個部分,但基本概念始終是一樣的。

希望這會有所幫助!

subprocess.poll()https://docs.python.org/2/library/subprocess.html#popen-objects

+0

這並未不會殺死這個過程。你需要添加os.killpg(os.getpgid(task.pid),signal.SIGTERM) – AaronS