来自Python子进程的Liveoutput/stream

2024-04-25 01:47:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python及其子进程库来检查使用strace调用的输出,这涉及到:

subprocess.check_output(["strace", str(processname)]) 

但是,这只给了我在调用的子流程已经完成之后的输出,这对我的用例来说是非常有限的。在

我需要一种来自进程的“流”或实时输出,因此我需要在进程仍在运行时读取输出,而不是仅在进程完成之后。在

有没有一种使用子流程库实现这一点的便捷方法? 我想每隔x秒进行一次投票,但在文档中没有找到任何关于如何实现这一点的提示。在

提前致谢。在


Tags: 方法文档output进程check流程投票用例
1条回答
网友
1楼 · 发布于 2024-04-25 01:47:56

根据documentation

Popen.poll()

Check if child process has terminated. Set and return returncode attribute.

基于此,您可以:

process = subprocess.Popen('your_command_here',stdout=subprocess.PIPE)
while True:
    output = process.stdout.readline()
    if process.poll() is not None and output == '':
        break
    if output:
        print (output.strip())
retval = process.poll()

这将循环读取stdout,并实时显示输出。在

相关问题 更多 >