【发布时间】:2021-12-12 17:57:51
【问题描述】:
有没有办法将 python 打印语句记录到文件中
方法一
我知道python file.py > data.txt,但这将记录崩溃错误,以防脚本崩溃或显示的最后一件事,并且在程序运行时不会记录任何内容,在我的情况下它将继续运行直到我杀死它
方法二
我可以使用另一个文件中的子进程来检查输出,但这对我也不起作用,因为我打算使用单个编译的 python exe(在 linux 的情况下为 elf)而不是两个 .py 脚本或带有.py
方法3
我尝试使用script data.txt ,但这似乎与第一种方法具有相同的效果
请注意,目标是在执行os.system("clear") 行之前记录终端中的所有内容以及上一个清除命令之后的所有内容
from time import time
from os import system
def log_terminal():
## log whatever text is displayed in the terminal to a text file in that current moment
pass
while True:
print (f"hello time is {int(time())}")
log_terminal()
os.system("clear")
【问题讨论】:
-
您可以编写自己的实用程序函数,该函数将内置
print函数包装起来,并将输出写入文本文件。 -
这能回答你的问题吗? Python output on file and terminal
-
我一直在寻找用 python 构建的东西,而不是自己实现