【问题标题】:Log terminal output to a text file python将终端输出记录到文本文件 python
【发布时间】: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 构建的东西,而不是自己实现

标签: python linux


【解决方案1】:

可以推荐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")

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多