如何使用Popen同时将内容写入标准输出和日志文件?

10 浏览
0 Comments

如何使用Popen同时将内容写入标准输出和日志文件?

我正在使用Popen调用一个连续将其stdout和stderr写入日志文件的shell脚本。有没有办法同时将日志文件连续输出(到屏幕),或者让shell脚本同时写入日志文件和stdout?

我基本上想在Python中做类似于这样的事情:

cat file 2>&1 | tee -a logfile #"cat file"将被替换为某个脚本

同样地,这将stderr/stdout一起管道到tee,它将它们同时写入stdout和我的日志文件。

我知道如何将stdout和stderr写入Python中的日志文件。我卡住的地方是如何将它们复制回屏幕上:

subprocess.Popen("cat file", shell=True, stdout=logfile, stderr=logfile)

当然,我可以像这样做,但是否有办法在没有tee和shell文件描述符重定向的情况下实现这一点?

subprocess.Popen("cat file 2>&1 | tee -a logfile", shell=True)

0