【问题标题】:capture stdout and stderr of process that runs an infinite loop捕获运行无限循环的进程的标准输出和标准错误
【发布时间】:2018-12-10 12:26:24
【问题描述】:

我想运行一个从 python 脚本运行无限循环(例如,启动数据库服务器)并捕获 stdout 和 stderr 的进程。我试过了,但p.communicate() 永远不会返回,显然是因为该过程需要先完成。

from subprocess import Popen, PIPE, STDOUT
cmd = "python infinite_loop.py"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print("the process is running")
stdout, stderr = p.communicate()
print(stdout)

我想以某种流媒体形式获得输出。例如,我可能想将每 100 个字符保存到一个新的日志文件中。我该怎么做?

【问题讨论】:

标签: python


【解决方案1】:

编辑:更接近于你已经拥有的东西,因为 asyncio 对于单个协程来说似乎有点过分了:

import sys
from subprocess import Popen, PIPE, STDOUT

args = (sys.executable, '-u', 'test4.py')
cmd = ' '.join(args)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
print("the process is running")

for line in iter(p.stdout.readline,''):
    line = line.rstrip()
    print(line)

原文:

我把东西扔在一起了。下面使用asyncio.subprocess 从子进程的输出中读取行,然后对它们进行处理(在这种情况下,只是print() 它们)。

子进程由args 指定,在我的例子中只是使用以下脚本(test4.py)以无缓冲模式运行另一个python实例:

import time
for _ in range(10):
    print(time.time(), flush=True)
    time.sleep(1)

我正在for 循环中睡觉,所以当程序完成时,很清楚这些行是单独进入还是同时进入。 (如果你不相信我,你可以把for循环改成while True:,这样永远不会结束。

“主管”脚本是:

import asyncio.subprocess
import sys


async def get_lines(args):
    proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE)

    while proc.returncode is None:
        data = await proc.stdout.readline()
        if not data: break
        line = data.decode('ascii').rstrip()
        # Handle line (somehow)
        print(line)


if sys.platform == "win32":
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()

args = (sys.executable, '-u', 'test4.py')
loop.run_until_complete(get_lines(args))
loop.close()

请注意,async def 是 Python 3.5+,but you could use @asyncio.coroutine in 3.4

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多