在Python 3中,我如何:
[live output from subprocess command不是重复的,因为那里的所有答案都不允许您的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")
请注意,我尚未考虑适当的清理操作-退出线程,关闭文件等。