鱼C论坛

 找回密码
 立即注册
查看: 2648|回复: 0

[技术交流] Python中获取报错文本

[复制链接]
发表于 2020-3-14 10:30:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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:
  1. def exceptionbox(msg=None, title=None):
  2.     """
  3.     Display a box that gives information about
  4.     an exception that has just been raised.

  5.     The caller may optionally pass in a title for the window, or a
  6.     msg to accompany the error information.

  7.     Note that you do not need to (and cannot) pass an exception object
  8.     as an argument.  The latest exception will automatically be used.

  9.     :param str msg: the msg to be displayed
  10.     :param str title: the window title
  11.     :return: None

  12.     """
  13.     if title is None:
  14.         title = "Error Report"
  15.     if msg is None:
  16.         msg = "An error (exception) has occurred in the program."

  17.     codebox(msg, title, ut.exception_format())
复制代码


那么事情就简单了,加一个renturn不就行了:
  1. return ut.exception_format()
复制代码

保存再运行,errortext=exceptionbox()能获取报错文本了,下一步获取时间,写入日志,OK。
但再想想,这程序换台电脑就不行了,得修改新电脑的“derived_boxes.py”才能正确运行,而且有的except后不需要显示错误信息而用了pass,可是也希望在日志里保留这些信息,以上方法显然不好用了。
于是继续分析easygui代码,找到了原始的错误信息代码,根据这些信息编写了一个函数recorderror,测试代码如下:
  1. import easygui as g
  2. import traceback,sys,datetime

  3. def recorderror(windows=True,errorfile='error.txt',):
  4.     errtime=datetime.datetime.today().strftime('%Y.%m.%d %H:%M:%S')
  5.     errtext="".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
  6.     if windows:
  7.         g.exceptionbox()
  8.     with open(errorfile,'a',encoding='utf-8') as f:
  9.         f.write(errtime+'\n'+errtext+'\n')

  10. try:
  11.     raise  TypeError
  12. except:
  13.     recorderror()
复制代码


带两个参数:默认windows=True会显示报错窗口并记录日志,=False会默默记录日志,errorfile可以指定日志文件名,默认是'error.txt'。

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-7 23:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表