How to make a subprocess.call timeout using python 2.7.6?(如何使用 python 2.7.6 使 subprocess.call 超时?)
问题描述
这可能已经被问过了,但我在使用 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 超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 python 2.7.6 使 subprocess.call 超时?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01