使用sys.excepthook函数进行全局异常的获取。

1. 使用MessageDialog实现异常显示;

2. 使用logger把捕获的异常信息输出到日志中;

步骤:定义异常处理函数, 并使用该函来替换掉系统的内置处理函数;

对于threading.py的异常捕获,需要对该文件进行一些改变:

如下:

try:
self.run()
except SystemExit:
if __debug__:
self._note("%s.__bootstrap(): raised SystemExit", self)
except:
if __debug__:
self._note("%s.__bootstrap(): unhandled exception", self)
# If sys.stderr is no more (most likely from interpreter
# shutdown) use self.__stderr. Otherwise still use sys (as in
# _sys) in case sys.stderr was redefined since the creation of
# self.
if _sys:
if id(_sys.excepthook) != id(_sys.__excepthook__):
exc_type, exc_value, exc_tb = self.__exc_info()
_sys.excepthook(exc_type, exc_value, exc_tb) _sys.stderr.write("Exception in thread %s:\n%s\n" %
(self.name, _format_exc()))
#-*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: 模块except hook handler
# Purpose: 全局捕获异常
#
# Author: ankier
#
# Created: 17-08-2013
# Copyright: (c) ankier 2013
# Licence: <your licence>
#------------------------------------------------------------------------------- import logging
import sys
import traceback
import datetime
import wx ## @detail 创建记录异常的信息
class ExceptHookHandler(object):
## @detail 构造函数
# @param logFile: log的输入地址
# @param mainFrame: 是否需要在主窗口中弹出提醒
def __init__(self, logFile, mainFrame = None):
self.__LogFile = logFile
self.__MainFrame = mainFrame self.__Logger = self.__BuildLogger()
#重定向异常捕获
sys.excepthook = self.__HandleException ## @detail 创建logger类
def __BuildLogger(self):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler(self.__LogFile))
return logger ## @detail 捕获及输出异常类
# @param excType: 异常类型
# @param excValue: 异常对象
# @param tb: 异常的trace back
def __HandleException(self, excType, excValue, tb):
# first logger
try:
currentTime = datetime.datetime.now()
self.__Logger.info('Timestamp: %s'%(currentTime.strftime("%Y-%m-%d %H:%M:%S")))
self.__Logger.error("Uncaught exception:", exc_info=(excType, excValue, tb))
self.__Logger.info('\n')
except:
pass # then call the default handler
sys.__excepthook__(excType, excValue, tb) err_msg = ''.join(traceback.format_exception(excType, excValue, tb))
err_msg += '\n Your App happen an exception, please contact administration.'
# Here collecting traceback and some log files to be sent for debugging.
# But also possible to handle the error and continue working.
dlg = wx.MessageDialog(None, err_msg, 'Administration', wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()

输出效果:

log输出文件:

python中如何用sys.excepthook来对全局异常进行捕获、显示及输出到error日志中的更多相关文章

  1. ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常

    在ASP.NET MVC中,通过应用程序生命周期中的Application_Error事件可以捕获到网站引发的所有未处理异常.本文作为学习笔记,记录了使用Global.asax文件的Applicati ...

  2. ng1中 如何用双向绑定 实现单向绑定的初始时不显示双括号效果?

    ng1中 如何用双向绑定 实现单向绑定(ng-bind就可以不显示{{}})的初始时不显示双括号效果? AngularJS 实例 页面加载时防止应用闪烁: <div ng-app="& ...

  3. Python中模块之sys的功能介绍

    sys模块的功能介绍 1. sys的变量 argv 命令行参数 方法:sys.argv 返回值:list 例如:test1.py文件中有两句语句1.import sys 2.print(sys.arg ...

  4. python中os与sys作用与区别

    https://www.cnblogs.com/cloak/p/11237285.html OS模块 在自动化测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告( ...

  5. Python中 os._exit() sys.exit() exit()区别

    Python退出程序的方式有两种:os._exit(), sys.exit() 1)os._exit() 直接退出 Python程序,其后的代码也不会继续执行. 2)sys.exit() 引发一个 S ...

  6. Python中os和sys模块中常用的方法

    os模块 os模块:该模块提供了一些方便使用操作系统相关功能的函数 os.remove() 删除文件 os.rename() 重命名文件 os.walk() 文件目录遍历器 os.chdir() 改变 ...

  7. Python常用模块之sys

    Python常用模块之sys sys模块提供了一系列有关Python运行环境的变量和函数. 常见用法 sys.argv 可以用sys.argv获取当前正在执行的命令行参数的参数列表(list). 变量 ...

  8. Python标准库之Sys模块使用详解

    sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. 处理命令行参数 在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称. 使用sy ...

  9. 多线程&多进程解析:Python、os、sys、Queue、multiprocessing、threading

    当涉及到操作系统的时候,免不了要使用os模块,有时还要用到sys模块. 设计到并行程序,一般开单独的进程,而不是线程,原因是python解释器的全局解释器锁GIL(global interpreter ...

随机推荐

  1. HTML的简单介绍

    <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Co ...

  2. angularJS constant和value

    angularJS可以通过constant(name,value)和value(name,value)对于创建服务也是很重要的. 相同点是:都可以接受两个参数,name和value. 区别: 1.co ...

  3. 【转】JavaScript对Json节点的增删改

    var json = { "age":24, "name":"cst" }; //修改Json中的age值,因为Json中存在age属性 j ...

  4. ALS数学点滴

    其中,$n_{u_i}$表示用户$i$评分的电影数目,$n_{m_j}$表示对电影$j$评分的用户数目.设$I_i$表示用户$i$所评分的电影集合,则$n_{u_i}$是$I_i$的基数,同样的,$I ...

  5. [PWA] 18. Clean the photo cache

    We cannot let photo always keep caching new data without clean the old data. If message is not displ ...

  6. [Flux] Component / Views

    The application will dislay a some catalogs, and each catalog has title image, description. Catalog: ...

  7. U口破解指令介绍.

  8. http方法

    http method(方法):1.get 从服务器获取资源2.post 向服务器发送资源3.put 向服务器推送资源4.delete 告诉服务器删除某个资源5.head 告诉服务器返回数据时不需要返 ...

  9. Java编程思想-注解生成外部例子代码

    如果本文帮助到您,请点击下面的链接,这是本人的网站,以示鼓励,谢谢!链接绝对安全! 本人的网站 java注解属于java中高大上的功能,许多开源框架都使用了java注解的功能.比如spring,hib ...

  10. 【转载】逃离adapter的地狱-针对多个View type的组合实现方案

    英文原文:JOE'S GREAT ADAPTER HELL ESCAPE 转载地址:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015 ...