如何读取子进程标准输出的第一个字节,然后在 Python 中丢弃其余字节?

How to read the first byte of a subprocess#39;s stdout and then discard the rest in Python?(如何读取子进程标准输出的第一个字节,然后在 Python 中丢弃其余字节?)
本文介绍了如何读取子进程标准输出的第一个字节,然后在 Python 中丢弃其余字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取子进程的标准输出的第一个字节,以了解它已经开始运行.之后我想丢弃所有进一步的输出,这样我就不必担心缓冲区了.

I'd like to read the first byte of a subprocess' stdout to know that it has started running. After that I'd like to discard all further output, so that I don't have to worry about the buffer.

最好的方法是什么?

澄清:我希望子进程继续与我的程序一起运行,我不想等待它终止或类似的事情.理想情况下,有一些简单的方法可以做到这一点,而无需使用 threadingforking 或 multiprocessing.

Clarification: I'd like the subprocess to continue running alongside my program, I don't want to wait for it to terminate or anything like that. Ideally there would be some simple way to do this, without resorting to threading, forking or multiprocessing.

如果我忽略输出流,或者 .close() 它,如果它发送的数据多于缓冲区可以容纳的数据,则会导致错误.

If I ignore the output stream, or .close() it, it causes errors if it is sent more data than it can fit in its buffer.

推荐答案

如果你使用 Python 3.3+,你可以为 stdout 使用 DEVNULL 特殊值和stderr 丢弃子进程输出.

If you're using Python 3.3+, you can use the DEVNULL special value for stdout and stderr to discard subprocess output.

from subprocess import Popen, DEVNULL

process = Popen(["mycmd", "myarg"], stdout=DEVNULL, stderr=DEVNULL)

或者,如果您使用的是 Python 2.4+,您可以使用以下方法进行模拟:

Or if you're using Python 2.4+, you can simulate this with:

import os
from subprocess import Popen

DEVNULL = open(os.devnull, 'wb')
process = Popen(["mycmd", "myarg"], stdout=DEVNULL, stderr=DEVNULL)

但是这并没有让您有机会读取标准输出的第一个字节.

However this doesn't give you the opportunity to read the first byte of stdout.

这篇关于如何读取子进程标准输出的第一个字节,然后在 Python 中丢弃其余字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)