Python子进程:如何即时输出并将输出和错误保存到文件? [重复]

问题描述 投票:0回答:1

我正在编写一个小的 Python 脚本来记录另一个 Python 程序的输出和错误,并像往常一样同时将它们打印在我的屏幕上。这段代码运行良好,除了它缓冲子进程 python 程序的输出并将它们长时间一起输出一次,而不是像往常一样立即打印:

subprocess.run(f"python {args.launch} 2>&1 | tee -a {file_path}", shell=True)

其中

args.lunch
是我的python程序的名称,
file_path
是日志文件。我尝试了一些现有的解决方案,但没有一个对我有用。

python linux subprocess
1个回答
0
投票

正如@rasjani 所提到的,解决这个问题的一种方法是使用

-u
标志

subprocess.run(f"python -u {args.launch} 2>&1 | tee -a {file_path}", shell=True)

我没有很好的解释为什么这有效。

或者,如果您将输入拆分为带有 shlex 的列表,如here所示,并删除

shell=True
,那么您也会得到所需的行为

# Assuming args.launch is a list of strings
subprocess.run(['python'] + args.launch + ['2>&1', '|', 'tee', '-a', file_path])
© www.soinside.com 2019 - 2024. All rights reserved.