简体   繁体   English

在不使用subprocess.PIPE的情况下在subprocess.check_call中捕获stderr

[英]Catch stderr in subprocess.check_call without using subprocess.PIPE

I'd like to do the following: 我想做以下事情:

  • shell out to another executable from Python, using subprocess.check_call 使用subprocess.check_call从Python转出另一个可执行文件
  • catch the stderr of the child process, if there is any 抓住子进程的stderr,如果有的话
  • add the stderr output to the CalledProcessError exception output from the parent process. 将stderr输出添加到父进程的CalledProcessError异常输出。

In theory this is simple. 理论上这很简单。 The check_call function signature contains a kwarg for stderr : check_call函数签名包含一个kwarg 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. 注意 :不要在此函数中使用stdout=PIPEstderr=PIPE 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. 由于在当前进程中没有读取管道,子进程可能会阻塞它是否为管道生成足够的输出以填充OS管道缓冲区。

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. 问题在于我几乎可以找到从子进程获取stderr的每个示例都提到使用subprocess.PIPE来捕获该输出。

How can you capture stderr from the child process without using subprocess.PIPE ? 如何在不使用subprocess.PIPE情况下从子进程中捕获stderr?

stdout and stderr can be assigned to almost anything that can receive data like a file-handle. stdoutstderr几乎可以分配给任何可以接收文件句柄等数据的东西。 you can even supply an open file_handle for writing to stdout and stderr : 你甚至可以提供一个打开的file_handle来写入stdoutstderr

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 . stdin也像文件句柄一样读取,使用next()读取每一行作为输入命令除了初始args之外还要发送。

its a very robust function. 它非常强大的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM