终止后,Python捕获子流程输出 [英] Python capture subprocess output after termination

查看:113
本文介绍了终止后,Python捕获子流程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在引发TimeoutExpired异常时获取子进程输出(在Windows上).有什么想法吗?

I am trying to get subprocess output (on Windows) at the time the TimeoutExpired exception is raised. Any ideas?

try:
    proc = subprocess.run(cmd,timeout=3)
except subprocess.TimeoutExpired:
    print(???)

推荐答案

您需要使用 Popen subprocess.PIPE 为了在超时到期时捕获进程输出.您特别需要 Popen.communicate . 这是一个例子

You need to use Popen and subprocess.PIPE in order to catch the process output when timeout expires. In particular Popen.communicate is what you need. Here is an example

proc = subprocess.Popen(["ping", "192.168.1.1"],
                        stdout=subprocess.PIPE)

try:
    output, error = proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
    proc.kill()
    output, error = proc.communicate()
    print(output)
    print(error)

这将打印过程输出直至超时.

This will print the process output up to the time out expiration.

这篇关于终止后,Python捕获子流程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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