我想在.txt或.log文件上打印终端上打印的所有内容,特别是错误。
在本例中,我在单击按钮时输入了一个错误,并希望将其捕获并打印到文件中。
在这种情况下,已知在单击按钮时会发生错误。但是,我希望在使用该程序时可能发生的任何错误被捕获并打印到文件中。
import tkinter as tk
def on_click():
# this error is made specifically to explain what I would like to achieve
print(int("string"))
# Create the window
win = tk.Tk()
win.geometry("500x300")
win.title("window")
# Create the button
tk.Button(win, text="Button", command=on_click).pack()
if __name__ == "__main__":
win.mainloop()这张照片是我想要捕捉的错误的一个例子。

发布于 2021-07-20 17:02:13
要理解,请尝试如下:
import logging
#option 1
logging.basicConfig(filename='log2.txt',filemode='a',format='%(asctime)s - %(message)s', level=logging.ERROR)
#option 2
def log_error(message):
with open("log.txt", "a+") as myfile:
myfile.write(f'ERROR : {message} \n')
try:
1/0
except Exception as e:
log_error(e)
logging.error("Exception occurred", exc_info=True)发布于 2021-07-20 17:06:10
在运行脚本时,可以使用文件描述符2重定向文件中的错误。
python script.py 2> error.txthttps://stackoverflow.com/questions/68458559
复制相似问题