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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)