python popen,stdout 在 strace 中显示,但在 popen.stdout.read() 中不显示

python popen, stdout shows in strace, but not in popen.stdout.read()

我有下面的 python 脚本,我正在使用它来尝试从一个没有适合所有内容的换行符的程序中读取。这允许读取而不用担心阻塞读取。但是,由于我对线程的了解还不够,我怀疑这就是我的问题所在。

import subprocess
import shlex
import os
import time
from threading import Thread
import queue


class NonBlockingStreamReader:
    def __init__(self, stream):
        """
        :param stream: the stream to read from.  Usually stdout or stderr.
        """
        self._s = stream
        self._q = queue.Queue()

        def _populate_queue(_stream, _queue):
            """Collect lines from 'stream' and put them in 'queue'"""
            while True:
                _char = _stream.read(1)
                if _char:
                    _queue.put(_char)
                else:
                    raise UnexpectedEndOfStream

        self._t = Thread(
            target=_populate_queue,
            args=(
                self._s,
                self._q
            )
        )
        self._t.daemon = True
        self._t.start() # Start collecting characters from the stream

    def readchar(self, timeout=None):
        try:
            _tmp = self._q.get(block=timeout is not None, timeout=timeout)
            return _tmp
        except queue.Empty:
            return None


class UnexpectedEndOfStream(Exception):
    pass


def main():
    proc = subprocess.Popen(
        shlex.split('strace -o /home/arts/dlm/trace_output.txt stdbuf -o0 /home/arts/dlm/test'),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    nbsr = NonBlockingStreamReader(proc.stdout)

    _data = b''
    while True:
        _char = nbsr.readchar(0.1)
        if not _char:
            break
        else:
            _data += _char
    print(_data.decode())

    proc.stdin.write(b'12345\n')

    _data = b''
    while True:
        _char = nbsr.readchar(5)
        if not _char:
            break
        else:
            _data += _char
    print(_data.decode())
    print('Annnnd done.')


if __name__ == '__main__':
    main()

这是 test 程序的预期输出:

Line 1 test
Line 2 test
Line 3 input: 12345      <--- input from user
Line 4 test: 12345

这是 strace 输出:

write(1, "Line 1 test", 11)             = 11
write(1, "\n", 1)                       = 1
write(1, "Line 2 test", 11)             = 11
write(1, "\n", 1)                       = 1
write(1, "Line 3 input: ", 14)          = 14
fstat(0, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb76716d000
read(0, "12345\n", 4096)                = 6
write(1, "Line 4 test: 12345\n\n", 20)  = 20
exit_group(1)                           = ?

这表明(至少对我而言)应用程序正在提供请求的输出。 read(0, "12345\n", 4096) 显示 proc.stdin.write(b'12345\n') 除非我遗漏了什么。下一行显示它读回了我期望的输出。然而,真正的输出是:

Line 1 test
Line 2 test
Line 3 input:

Annnnd done.

如果我在 _char = _stream.read(1) 之后放置一些打印语句,它什么也不会显示。如果我将它们添加到 readchar 函数中,那么它会显示 None.

有些东西正在破坏 stdout,所以无论它去哪里,它都不会进入管道。有人可以指导我正确的方向吗?

想通了。需要 bufsize=0 作为 Popen.

的参数

你的第二个读取循环有两个问题:

  • 它在空 _data 而不是 _char 时中断,并且 _data 在循环的顶部设置为 b'',所以它总是会在不写入的情况下退出_data.
  • 的任何内容
  • 一旦 reader 的缓冲区为空,它就会中断,这可能是在子进程的整个输出被写入或读取之后,也可能不是,这取决于进程的时间和涉及线程。

您可能希望在 reader 中设置一个 EOF 标志而不是在那里引发 UnexpectedEndOfStream 然后将循环基于该标志(或者更确切地说,基于该标志的派生条件正在设置且队列为空)。