问题描述
这可能已经被问过了,但我在使用 python 2.7 时找不到任何关于 subprocess.call 超时的信息
This has probably been asked but I cannot find anything regarding a subprocess.call timeout when using python 2.7
推荐答案
我一直使用 2.7 完成超时的一个简单方法是使用 subprocess.poll()
和 time.sleep()
延迟.这是一个非常基本的例子:
A simple way I've always done timeouts with 2.7 is utilizing subprocess.poll()
alongside time.sleep()
with a delay. Here's a very basic example:
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 秒.您可以随心所欲地玩弄这部分,但基本概念始终相同.
If you set x = 600
, then your timeout would amount to 10 minutes. While task.poll()
will query whether or not the process has terminated. time.sleep(delay)
will sleep for 1 second in this case, and then decrement the timeout by 1 second. You can play around with that part to your heart's content, but the basic concept is the same throughout.
希望这会有所帮助!
subprocess.poll()
https://docs.python.org/2/library/subprocess.html#popen-objects
这篇关于如何使用 python 2.7.6 使 subprocess.call 超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!