执行打印到标准输出的子进程,等待文本,然后继续执行主脚本

问题描述 投票:1回答:1

在Python 3中,我如何:

  1. 执行一个过程,并将其标准输出打印到标准输出,
  2. 监视标准输出以等待一些文本,然后
  3. 继续执行我的Python程序,而不会在找到文本后终止进程,也不会停止将其打印到stdout。

[live output from subprocess command不是重复的,因为那里的所有答案都不允许您的Python代码继续运行,并且仍然打印该进程的标准输出。

我想解决方案将涉及某种线程,协程或任务。

python subprocess
1个回答
0
投票
一种相对简单的方法是,在完成处理后,启动一个新线程将进程的标准输出复制到Python的标准输出。这是运行webpack-dev-server并从中抓取URL的示例(未实际实现):

#!/usr/bin/env python3 import subprocess import sys import os from threading import Thread from typing import IO def pipe(a: IO[bytes], b: IO[bytes]): for x in a: b.write(x) b.flush() process = subprocess.Popen( [ "node_modules/.bin/webpack-dev-server", # Note that I had to add --colour because for some reason # webpack-dev-server detects stdout as supporting colour, # but not stderr. "--color", # This prints a progress bar using ANSI escape characters # which works too! "--progress", ], cwd=".", env=dict(os.environ, NODE_ENV="development"), stdout=subprocess.PIPE, ) for line in process.stdout: sys.stdout.buffer.write(line) # Flush is necessary otherwise stdout will buffer more # than one line. sys.stdout.buffer.flush() # Process the text however you want. if b"Project is running at" in line: print("Server started at address ??") break # Start a thread to do the pipe copying. thread = Thread(target=pipe, args=(process.stdout, sys.stdout.buffer)) thread.start() print("Now we can do other stuff and the process will continue to print to stdout")

请注意,我尚未考虑适当的清理操作-退出线程,关闭文件等。    
© www.soinside.com 2019 - 2024. All rights reserved.