马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
最近编了一个小程序,为了防止出错,用了easygui的exceptionbox()来显示错误,然后考虑把这些报错写入到日志文件error.txt里去,原以为exceptionbox()会返回错误文本,结果errortext=exceptionbox()返回值是None ,查找“C:\Users\用户\AppData\Local\Programs\Python\Python38\Lib\site-packages\easygui-0.98.0_UNRELEASED-py3.8.egg\easygui\boxes”下的“derived_boxes.py”,发现原来exceptionbox()原来调用ccbox显示错误信息后没有return,难怪返回默认值None:def exceptionbox(msg=None, title=None):
"""
Display a box that gives information about
an exception that has just been raised.
The caller may optionally pass in a title for the window, or a
msg to accompany the error information.
Note that you do not need to (and cannot) pass an exception object
as an argument. The latest exception will automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None
"""
if title is None:
title = "Error Report"
if msg is None:
msg = "An error (exception) has occurred in the program."
codebox(msg, title, ut.exception_format())
那么事情就简单了,加一个renturn不就行了:return ut.exception_format()
保存再运行,errortext=exceptionbox()能获取报错文本了,下一步获取时间,写入日志,OK。
但再想想,这程序换台电脑就不行了,得修改新电脑的“derived_boxes.py”才能正确运行,而且有的except后不需要显示错误信息而用了pass,可是也希望在日志里保留这些信息,以上方法显然不好用了。
于是继续分析easygui代码,找到了原始的错误信息代码,根据这些信息编写了一个函数recorderror,测试代码如下:import easygui as g
import traceback,sys,datetime
def recorderror(windows=True,errorfile='error.txt',):
errtime=datetime.datetime.today().strftime('%Y.%m.%d %H:%M:%S')
errtext="".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
if windows:
g.exceptionbox()
with open(errorfile,'a',encoding='utf-8') as f:
f.write(errtime+'\n'+errtext+'\n')
try:
raise TypeError
except:
recorderror()
带两个参数:默认windows=True会显示报错窗口并记录日志,=False会默默记录日志,errorfile可以指定日志文件名,默认是'error.txt'。
|