且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用实时输出运行python子进程?

更新时间:2022-05-12 23:36:26

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