如何将python输出重定向到python控制台和Windows中的文本文件

2024-06-20 15:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本_1,它将用于使用子进程调用另一个python脚本_2。当我这样做时,我可以在python控制台(或cmd)上看到许多print语句和输出。如何在python控制台上显示输出的同时将输出重定向到一个文件。在

基本上,我需要一个windows可执行命令来执行Linux的' | & tee '命令。 我试了很多方法,但都没用。在

谢谢你的帮助。:)


Tags: 文件方法命令脚本cmd进程linuxwindows
1条回答
网友
1楼 · 发布于 2024-06-20 15:18:30

您可以使用CMD:
python script.py >> out.txt
要以编程方式重定向输出,请执行以下操作: 由于python代码的输出是stdout,因此可以将其重定向到一个文件中,因此将创建一个包含输出内容的文件,请注意,建议将原始的stout存储在var中,以防以后要向shell输出某些内容: 在

import sys
#store the original stdout object
original = sys.stdout
#open a txt file to store the stdout
sys.stdout = open('stdout.txt', 'w')

#Goes to stdout.txt
print('this is a txt file')

#restore the original stdout
sys.stdout = original

#Goes to shell output
print('this is python interpreter')

更多信息:
Cannot redirect output when I run Python script on Windows using just script's name
https://stackoverflow.com/a/3021809/8094047
https://www.blog.pythonlibrary.org/2016/06/16/python-101-redirecting-stdout/

相关问题 更多 >