【问题标题】:How to run python subprocess with real-time output?如何运行具有实时输出的python子进程?
【发布时间】:2020-06-25 05:43:11
【问题描述】:

当我在 Python 中运行 shell 命令时,在命令完成之前它不会显示输出。我运行的脚本需要几个小时才能完成,我想在它运行时查看进度。 如何让 python 运行它并实时显示输出?

【问题讨论】:

    标签: python subprocess output real-time


    【解决方案1】:

    使用以下函数运行您的代码。在这个例子中,我想运行一个带有两个参数的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2011-04-04
      • 2023-01-19
      • 2018-05-20
      • 2015-06-08
      • 2019-06-03
      • 1970-01-01
      相关资源
      最近更新 更多