将模块“子进程"与超时一起使用 [英] Using module 'subprocess' with timeout

查看:66
本文介绍了将模块“子进程"与超时一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是Python代码,用于运行返回其stdout数据的任意命令,或在非零退出代码上引发异常:

Here's the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:

proc = subprocess.Popen(
    cmd,
    stderr=subprocess.STDOUT,  # Merge stdout and stderr
    stdout=subprocess.PIPE,
    shell=True)

communicate用于等待进程退出:

stdoutdata, stderrdata = proc.communicate()

subprocess模块不支持超时-杀死运行时间超过X秒的进程的能力-因此,communicate可能要花很长时间才能运行.

The subprocess module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, communicate may take forever to run.

在打算在Windows和Linux上运行的Python程序中实现超时的最简单方式是什么?

What is the simplest way to implement timeouts in a Python program meant to run on Windows and Linux?

推荐答案

在Python 3.3+中:

In Python 3.3+:

from subprocess import STDOUT, check_output

output = check_output(cmd, stderr=STDOUT, timeout=seconds)

output是一个字节字符串,其中包含命令的合并stdout,stderr数据.

output is a byte string that contains command's merged stdout, stderr data.

check_output 在非问题文本中指定的零退出状态,与proc.communicate()方法不同.

我删除了shell=True,因为它经常被不必要地使用.如果cmd确实需要,可以随时将其添加回去.如果添加shell=True,即子进程产生自己的后代; check_output()可以比超时指示晚得多返回,请参见子进程超时失败.

I've removed shell=True because it is often used unnecessarily. You can always add it back if cmd indeed requires it. If you add shell=True i.e., if the child process spawns its own descendants; check_output() can return much later than the timeout indicates, see Subprocess timeout failure.

通过2.a的 subprocess32 反向端口,可以在Python 2.x上使用超时功能3.2+子流程模块.

The timeout feature is available on Python 2.x via the subprocess32 backport of the 3.2+ subprocess module.

这篇关于将模块“子进程"与超时一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆