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

2023-07-21Python开发问题
20

本文介绍了如何使用 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 超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11