有没有办法将python打印语句记录到文件中
方法1我知道python file.py > data.txt
,但这将记录崩溃错误,以防脚本崩溃或最后显示的内容,并且在程序运行时不会记录任何内容,在我的情况下,它将继续运行,直到我杀死它
方法2我可以使用另一个文件中的子进程来检查输出,但这对我来说也不起作用,因为我计划使用一个编译的python-exe(在linux的情况下是elf(,而不是两个.py
脚本或一个带有.py
的exe
方法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")
可以推荐logging
来执行此操作。简单示例:
import logging
logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')
def we_prints(data):
logging.info(data)
print(data)
we_prints("some data we are logging")