【发布时间】:2020-06-25 05:43:11
【问题描述】:
当我在 Python 中运行 shell 命令时,在命令完成之前它不会显示输出。我运行的脚本需要几个小时才能完成,我想在它运行时查看进度。 如何让 python 运行它并实时显示输出?
【问题讨论】:
标签: python subprocess output real-time
当我在 Python 中运行 shell 命令时,在命令完成之前它不会显示输出。我运行的脚本需要几个小时才能完成,我想在它运行时查看进度。 如何让 python 运行它并实时显示输出?
【问题讨论】:
标签: python subprocess output real-time
使用以下函数运行您的代码。在这个例子中,我想运行一个带有两个参数的 R 脚本。您可以将 cmd 替换为任何其他 shell 命令。
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)
【讨论】: