How to run python subprocess with real-time output?

荒凉一梦 提交于 2021-02-11 18:18:20

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/62568597/how-to-run-python-subprocess-with-real-time-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!