如何使用python 2.7.6进行subprocess.call超时?

use*_*496 12 python subprocess timeout python-2.7

可能有人问过,但是在使用python 2.7时我找不到任何关于subprocess.call超时的信息

小智 11

一个简单的方法,我一直在做超时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
Run Code Online (Sandbox Code Playgroud)

如果设置x = 600,则超时将达到10分钟.同时task.poll()将查询进程是否已终止.time.sleep(delay)在这种情况下将休眠1秒钟,然后将超时减少1秒.你可以根据自己的内容来玩这个部分,但基本概念始终如一.

希望这可以帮助!

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

  • 这不会杀死这个过程.你需要添加os.killpg(os.getpgid(task.pid),signal.SIGTERM) (3认同)