使用Python Subprocess.run将stdout重定向到Terminal和log .txt文件

问题描述

我正在尝试运行命令并将输出重定向到.txt文件,并能够使用subprocess.run()在终端中看到它。我以前使用2>&1 | file.txt完成此操作,但想通过subprocess.run()和shell = False

模仿这种味道

我目前能够成功地将stdout重定向.txt.,但是我也希望能够在终端中看到它。有没有办法做到这一点?我在Python 3.6

        with open(model_dest_dir + 'Deepspeech_progress.txt','w') as f:
             train_model = subprocess.run(train_cmds,shell = False,cwd = '/home/',env =  export_dict,stdout = f)
        #for stdout_line in iter(train_model.stdout.readline,b''):
        #    print(stdout_line)
        f.close()

解决方法

看起来我有一个可行的解决方案,尽管不是Traceback (most recent call last): File "zoosimulation.py",line 22,in <module> tiger = Tiger() File "zoosimulation.py",line 12,in __init__ super().__init__(type,diet,location,hunger,energy,sick) NameError: name 'diet' is not defined 。我必须像这样使用subprocess.run()

Popen