Popen混合数据流? [英] Popen mixed data stream?

查看:100
本文介绍了Popen混合数据流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows上使用Popen和Pipes遇到了问题.我认为Popen在stdout和stderr之间混合了数据. 当我的程序仅读取stdout时,一切正常,但是当我读取stdout和stderr时,来自stdout的某些数据将被抛出到stderr. 我的读取方法:

I've got problem with Popen and Pipes on Windows. I think Popen mixed data between stdout and stderr. When my program reads only stdout everything is OK but when I read stdout and stderr some data from stdout is thrown to stderr. My read method:

    for line in iter(self._read_obj.readline, b''):
        self._queue.put(line)
        sleep(.2)

其中self._read_obj是stderr还是stdout. 你知道我该怎么解决吗?

Where self._read_obj is either stderr or stdout. Do you know how can I solve this?

推荐答案

from subproccess import *
x = Popen('sh /root/script.sh', stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True)
print x.stdout.readline()
print x.stderr.readline()

由于您没有发布任何相关代码,因此它的外观如下. 请注意,即使没有要读取的内容,readline仍会为您提供输出,因为stderr有时会挂起"等待输出,但这是您使用子流程时要走的路.

Since you don't posted any relevant code, here's how it should look. Note that readline will still give you output even tho there is none to fetch, as to stderr sometimes "hangs" waiting for output, but this is the way to go if you're using subprocess.

from subprocess import PIPE, Popen
x = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False)
while 1:
    if x.poll() != None:
        break
    _queue.put(x.stdout.readline())
    sleep(0.2)

类似的事情应该起作用. 如果您不需要将两个输出分开,而只想读取数据并将其放在队列中,则可以执行以下操作:

Something like that should work. If you don't need to separate the two outputs, and you just want to read the data and att it to a queue, you can do:

x = Popen(['ls', '-l'], stdout=PIPE, stderr=STDOUT, stdin=PIPE, shell=False)

这是我通常做的事

(我并不是说这是事物的最佳实践,但它确实有效)

Here's what i normally do

(and i'm not saying this is the best practice of things, but it works)

from threading import Thread, enumerate
from subprocess import Popen, PIPE
from time import sleep

class nonBlockingStderr(Thread):
    def __init__(self, handle):
        self.handle = handle
        self.stderrOutput = []
        Thread.__init__(self)
        self.start()
    def stderr(self):
        if len(self.stderrOutput) <= 0:
            return ''
        else:
            ret = self.stderrOutput[0]
            self.stderrOutput = self.stderrOutput[1:]
            return ret
    def run(self):
        while 1:
            line = self.handle.readline()
            if len(line) > 0:
                self.stderrOutput.append(line)
            sleep(0.1)

from subprocess import PIPE, Popen
x = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False)
errHandle = nonBlockingStderr(x.stderr)
while 1:
    if x.poll() != None:
        break
    _queue.put(errHandle.stderr())
    _queue.put(x.stdout.readline())
    sleep(0.2)

这篇关于Popen混合数据流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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