如何检索具有大数据缓冲区的 shell 命令的 stderr? [英] How do I retrieve stderr for a shell command with a large data buffer?

查看:65
本文介绍了如何检索具有大数据缓冲区的 shell 命令的 stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 子进程模块声明了关于 communicate() 功能:

Python subprocess module states regarding the communicate() function:

注意

读取的数据是缓存在内存中的,所以如果不使用这种方法数据量很大或无限制.

The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

如何执行读取大量数据的进程(例如,communicate() 是禁忌的)但仍然可以访问 stderr 输出?

How can I execute a process that reads a lot of data (e.g. communicate() is contraindicated) and yet still have access to the stderr output?

推荐答案

要在可用时单独获得可能不受限制的子进程的 stdout/stderr 输出,您可以使用 twisted spawnProcess():

To get possibly unlimited subprocess' stdout/stderr output separately as soon as it becomes available, you could use twisted spawnProcess():

#!/usr/bin/env python
from twisted.internet import protocol
from twisted.internet import reactor

class ProcessProtocol(protocol.ProcessProtocol):
    def outReceived(self, data):
        print 'got stdout:', data
    def errReceived(self, data):
        print 'got stderr:', data
    def processEnded(self, reason):
        reactor.stop()

process = ProcessProtocol()
reactor.spawnProcess(process, 'cmd', ['cmd', 'arg 1', 'arg 2'])
reactor.run()

另一种方法是使用线程,例如 teed_call() 或使用特定于操作系统的代码例如,fcntl 模块使 POSIX 系统上的管道无阻塞 或使用 Windows 上与命名管道重叠的 I/O.

An alternative is to use threads e.g., teed_call() or use OS specific code e.g., fcntl module to make the pipes non-blocking on POSIX systems or use Overlapped I/O with named pipes on Windows.

这篇关于如何检索具有大数据缓冲区的 shell 命令的 stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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