Python中如何实时打印外部脚本输出,无需等待脚本执行完成?
实时获取外部Python脚本输出的解决方法
问题描述
运行外部脚本demo_print.py时,主程序main.py会等待脚本执行完毕后才一次性输出所有内容,需要实现无需等待脚本完成即可实时打印输出。
原脚本代码
demo_print.py
import time for i in range(10): print(f"print {i}") time.sleep(1)
main.py
def run_command(command): process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output.decode('UTF-8').strip()) rc = process.poll() return rc def main(argv): cmd = "demo_print.py" run_command(cmd) if __name__ == '__main__': main(sys.argv)
原因分析
Python的print函数默认使用缓冲输出机制,当输出目标不是终端(比如被subprocess捕获)时,缓冲区会积累内容直到满了才刷新,导致主程序无法实时获取输出。此外主程序的命令调用和输出读取逻辑也有优化空间。
解决方案
1. 修改子脚本,强制刷新输出缓冲区
在demo_print.py的print语句中添加flush=True参数,让每次输出立即写入标准输出:
import time for i in range(10): print(f"print {i}", flush=True) time.sleep(1)
也可以在脚本开头全局设置行缓冲模式,避免每次print都加参数:
import sys import time # 设置stdout为行缓冲模式 sys.stdout = open(sys.stdout.fileno(), 'w', buffering=1) for i in range(10): print(f"print {i}") time.sleep(1)
2. 优化主程序的调用与读取逻辑
调整main.py的代码,确保命令正确执行并实时读取输出:
import subprocess import shlex import sys def run_command(command): # 开启行缓冲,直接读取字符串,合并stderr到stdout process = subprocess.Popen( shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1 ) # 逐行读取输出并打印 for line in process.stdout: print(line.strip()) # 等待进程结束并返回退出码 return process.wait() def main(argv): # 指定Python解释器执行脚本,避免环境识别问题 cmd = "python demo_print.py" run_command(cmd) if __name__ == '__main__': main(sys.argv)
关键说明
flush=True或行缓冲设置:强制Python每次输出后立即刷新缓冲区,确保内容能被主程序实时捕获。- 主程序
bufsize=1:开启行缓冲模式,让subprocess按行读取输出,避免积累数据。 - 指定Python解释器:不同环境下直接运行脚本文件名可能无法正确触发解释器,显式指定
python demo_print.py更可靠。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

