为什么我的子流程的输出没有被打印出来?

Why is the output of my subprocess not being printed?

这是我从子进程异步读取 stdin/stdout 并从 Python 打印它的最佳尝试:

import asyncio
import subprocess

from asyncio.subprocess import STDOUT, PIPE, DEVNULL


async def start_stream():
    return await asyncio.create_subprocess_shell(
        'watch ls /proc',
        stdout=PIPE,
        stderr=PIPE,
        limit=1024
    )


async def spawn():
    ev_proc = await start_stream()
    while True:
        stdout, stderr = await ev_proc.communicate()
        print(stdout, stderr)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(spawn())

为什么打印函数没有输出任何东西?

您的 watch 进程永远不会终止并且 communicate() 等待进程终止,因此 stdout 永远不会到达您的脚本。
https://docs.python.org/3/library/asyncio-subprocess.html

coroutine communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

尝试以下受 启发的代码。 它使用 pipe_data_received 然后 len > 16 只是为了防止打印空行。

SubprocessProtocol.pipe_data_received(fd, data)

Called when the child process writes data into its stdout or stderr pipe. fd is the integer file descriptor of the pipe. data is a non-empty bytes object containing the data.

import asyncio

class SubprocessProtocol(asyncio.SubprocessProtocol):
    def pipe_data_received(self, fd, data):
        if fd == 1:
            text = data.decode()
            if len(text.strip()) > 16:
                print(text.strip())

    def process_exited(self):
        loop.stop()

loop = asyncio.get_event_loop()


ls = loop.run_until_complete(loop.subprocess_exec(
    SubprocessProtocol, 'watch', 'ls', '/proc'))
loop.run_forever()