[英]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
協程通信(輸入=無)
與進程交互:將數據發送到stdin。 從stdout和stderr讀取數據,直到到達文件末尾。 等待進程終止。
嘗試以下受https://stackoverflow.com/a/24435988/2776376啟發的代碼。 它使用pipe_data_received
,然后len > 16
只是為了防止打印空行。
SubprocessProtocol.pipe_data_received(fd,數據)
當子進程將數據寫入其stdout或stderr管道時調用。 fd是管道的整數文件描述符。 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.