如何使用实时输出运行python子进程? [英] How to run python subprocess with real-time output?
本文介绍了如何使用实时输出运行python子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在 Python 中运行 shell 命令时,它在命令完成之前不会显示输出.我运行的脚本需要几个小时才能完成,我想在它运行时查看进度.如何让 python 运行它并实时显示输出?
When I run a shell command in Python it does not show the output until the command is finished. the script that I run takes a few hours to finish and I'd like to see the progress while it is running. How can I have python run it and show the outputs in real-time?
推荐答案
使用以下函数运行您的代码.在这个例子中,我想运行一个带有两个参数的 R 脚本.您可以将 cmd 替换为任何其他 shell 命令.
Use the following function to run your code. In this example, I want to run an R script with two arguments. You can replace cmd with any other shell command.
from subprocess import Popen, PIPE
def run(command):
process = Popen(command, stdout=PIPE, shell=True)
while True:
line = process.stdout.readline().rstrip()
if not line:
break
print(line)
cmd = f"Rscript {script_path} {arg1} {arg2}"
run(cmd)
这篇关于如何使用实时输出运行python子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文