在不使用 subprocess.PIPE 的情况下在 subprocess.check_call 中捕获 stderr [英] Catch stderr in subprocess.check_call without using subprocess.PIPE

查看:44
本文介绍了在不使用 subprocess.PIPE 的情况下在 subprocess.check_call 中捕获 stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作:

  • 使用 subprocess.check_call
  • 从 Python 执行到另一个可执行文件
  • 捕获子进程的stderr,如果有的话
  • 将 stderr 输出添加到来自父进程的 CalledProcessError 异常输出.

理论上这很简单.check_call 函数签名包含一个用于 stderr 的 kwarg:

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

但是,紧接着文档包含以下警告:><块引用>

注意:请勿将stdout=PIPEstderr=PIPE 与此功能一起使用.由于当前进程没有读取管道,如果子进程生成足够的输出到管道以填满操作系统管道缓冲区,它可能会阻塞.

问题是,我能找到的几乎每个从子进程获取 stderr 的示例都提到使用 subprocess.PIPE 来捕获该输出.

如何在不使用 subprocess.PIPE 的情况下从子进程捕获 stderr?

解决方案

stdoutstderr 可以分配给几乎任何可以接收数据的东西,比如文件句柄.你甚至可以提供一个打开的 file_handle 来写入 stdoutstderr:

file_handle = open('some_file', 'w')subprocess.check_call(args, *, stdin=None, stdout=file_handle, stderr=file_handle, shell=False)

现在每一行输出都进入同一个文件,或者你可以为每个输出一个不同的文件.

stdin 也读起来像一个文件句柄,使用 next() 读取每一行作为除了初始 args 之外要发送的输入命令.

这是一个非常强大的功能.

I'd like to do the following:

  • shell out to another executable from Python, using subprocess.check_call
  • catch the stderr of the child process, if there is any
  • add the stderr output to the CalledProcessError exception output from the parent process.

In theory this is simple. The check_call function signature contains a kwarg for stderr:

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

However, immediately below that the documentation contains the following warning:

Note: Do not use stdout=PIPE or stderr=PIPE with this function. As the pipes are not being read in the current process, the child process may block if it generates enough output to a pipe to fill up the OS pipe buffer.

The problem is that pretty much every example I can find for getting stderr from the child process mentions using subprocess.PIPE to capture that output.

How can you capture stderr from the child process without using subprocess.PIPE?

解决方案

stdout and stderr can be assigned to almost anything that can receive data like a file-handle. you can even supply an open file_handle for writing to stdout and stderr:

file_handle = open('some_file', 'w')

subprocess.check_call(args, *, stdin=None, stdout=file_handle, stderr=file_handle, shell=False)

now every line of output goes to same file, or you could have a different file for each.

stdin also reads like a filehandle, using the next() to read each line as an input command to be sent on in addition to the initial args.

its a very robust function.

这篇关于在不使用 subprocess.PIPE 的情况下在 subprocess.check_call 中捕获 stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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