• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sys.__excepthook__函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sys.__excepthook__函数的典型用法代码示例。如果您正苦于以下问题:Python __excepthook__函数的具体用法?Python __excepthook__怎么用?Python __excepthook__使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了__excepthook__函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: info

def info(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        sys.__excepthook__(type, value, tb)
    else:
        import ipdb
        traceback.print_exception(type, value, tb)
        ipdb.post_mortem(tb)
开发者ID:mobiusklein,项目名称:glycan_profiling,代码行数:7,代码来源:__main__.py


示例2: uncaught_excepthook

def uncaught_excepthook(*args):
    sys.__excepthook__(*args)
    if __debug__:
        from pprint import pprint
        from types import BuiltinFunctionType, ClassType, ModuleType, TypeType
        tb = sys.last_traceback
        while tb.tb_next: tb = tb.tb_next
        print('\nDumping locals() ...')
        pprint({k:v for k,v in tb.tb_frame.f_locals.items()
                    if not k.startswith('_') and
                       not isinstance(v, (BuiltinFunctionType,
                                          ClassType, ModuleType, TypeType))})
        if sys.stdin.isatty() and (sys.stdout.isatty() or sys.stderr.isatty()):
            try:
                import ipdb as pdb  # try to import the IPython debugger
            except ImportError:
                import pdb as pdb
            print '\nStarting interactive debug prompt ...'
            pdb.pm()
    else:
        import traceback
        from dialogs import ErrorDialog
        ErrorDialog(_('Unexpected error'),
                    _('<b>The installer has failed with the following unexpected error. Please submit a bug report!</b>'),
                    '<tt>' + '\n'.join(traceback.format_exception(*args)) + '</tt>')
    sys.exit(1)
开发者ID:asacopeich,项目名称:live-installer,代码行数:26,代码来源:main.py


示例3: exceptHook

def exceptHook(exc_type, exc_value, exc_traceback):
	if issubclass(exc_type, KeyboardInterrupt):
		sys.__excepthook__(exc_type, exc_value, exc_traceback)
		return
	mainLogger = logging.getLogger("Main")			# Main logger
	mainLogger.critical('Uncaught exception!')
	mainLogger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
开发者ID:GDXN,项目名称:MangaCMS,代码行数:7,代码来源:logSetup.py


示例4: write_to_file

 def write_to_file(exc_type, exc, tb):
     sys.__excepthook__(exc_type, exc, tb)
     fn = "yt_traceback%s" % file_suffix
     with open(fn, "w") as fhandle:
         traceback.print_exception(exc_type, exc, tb, file=fhandle)
         print("Wrote traceback to %s" % fn)
     MPI.COMM_WORLD.Abort(1)
开发者ID:amacki3,项目名称:yt-scripts,代码行数:7,代码来源:parallel_analysis_interface.py


示例5: debug_exceptions

def debug_exceptions(type, value, tb):
    base_name = "dump"

    # find a browser object in the stack
    frames = inspect.getinnerframes(tb)
    frames.reverse() # reversed because we want the innermost first
    browser = None
    for frame, _, _, _, _, _ in frames:
        for v in inspect.getargvalues(frame).locals.values():
            if isinstance(v, Browser):
                browser = v
                break

    localest = frames[0][0]

    # stick a trace in a file
    with open(base_name + '.trace', 'w') as tracefile:
        tracefile.write("Locals:\n")
        pprint(localest.f_locals, tracefile)
        tracefile.write("\n")
        if browser is not None:
            tracefile.write("URL: %s\n" % browser.url)
            tracefile.write("\n")
        traceback.print_tb(tb, file=tracefile)

    if browser is not None:
        browser.save(base_name + '.html')

    # then call the default handler
    sys.__excepthook__(type, value, tb)
开发者ID:ahri,项目名称:financials,代码行数:30,代码来源:debug.py


示例6: _global_except_hook

def _global_except_hook(exctype, value, traceback):
    """Catches an unhandled exception and call MPI_Abort()."""
    try:
        if _orig_except_hook:
            _orig_except_hook(exctype, value, traceback)
        else:
            sys.__excepthook__(exctype, value, traceback)

    finally:
        import mpi4py.MPI
        rank = mpi4py.MPI.COMM_WORLD.Get_rank()
        sys.stderr.write('\n')
        sys.stderr.write('******************************************\n')
        sys.stderr.write('ChainerMN: \n')
        sys.stderr.write('   Uncaught exception on rank {}. \n'.format(rank))
        sys.stderr.write('   Calling MPI_Abort() to shut down MPI...\n')
        sys.stderr.write('******************************************\n')
        sys.stderr.write('\n\n')
        sys.stderr.flush()

        try:
            import mpi4py.MPI
            mpi4py.MPI.COMM_WORLD.Abort(1)
        except Exception as e:
            # Something is completely broken...
            # There's nothing we can do any more
            sys.stderr.write(
                'Sorry, failed to stop MPI and the process may hang.\n')
            sys.stderr.flush()
            raise e
开发者ID:asi1024,项目名称:chainer,代码行数:30,代码来源:global_except_hook.py


示例7: exch

 def exch(e, v, tb):
     if e == NameError:
         token = v.args[0].split("'")[1]
         globals()[token] = 0
         print('worked:', token);
         goto.jump_to(tb.tb_next.tb_lineno + 1, tb.tb_next.tb_frame)
     sys.__excepthook__(e, v, tb)
开发者ID:amrali,项目名称:bits,代码行数:7,代码来源:new_language.py


示例8: fileexcepthook

def fileexcepthook(exception_type, exception_value, traceback_object):
    # also call the standard exception handler to have prints on the console
    sys.__excepthook__(exception_type, exception_value, traceback_object)

    separator = '-' * 80
    log_dir = QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.AppDataLocation)[0]
    logFile = os.path.join(log_dir, "friture.log")

    versionInfo="Friture " + friture.__versionXXXX__

    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")

    tbinfofile = io.StringIO()
    traceback.print_tb(traceback_object, None, tbinfofile)
    tbinfofile.seek(0)
    tbinfo = tbinfofile.read()
    errmsg = '%s: \n%s' % (str(exception_type), str(exception_value))
    sections = [separator, timeString, separator, errmsg, separator, tbinfo, separator, versionInfo]
    msg = '\n'.join(sections)

    try:
        os.makedirs(log_dir, exist_ok=True)
        with open(logFile, "w") as f:
            f.write(msg)
    except IOError as e:
        print(e)
        pass

    notice = \
        """An unhandled exception occurred. Please report the problem\n"""\
        """on GitHub or via email to <%s>.\n"""\
        """A log has been written to "%s".\n\nError information:\n""" % \
        ("[email protected]", logFile)

    return str(notice)+str(msg)
开发者ID:MihailJP,项目名称:friture,代码行数:35,代码来源:exceptionhandler.py


示例9: exception_handler

            def exception_handler(type, value, traceback):
                settings_diff = diff_config(
                    load_config(DEFAULT_CONFIG, defaults=False),
                    config,
                    exclude=set([("lancet", "sentry_dsn")]),
                )

                sys.__excepthook__(type, value, traceback)

                if type in IGNORED_EXCEPTIONS:
                    return

                click.echo()
                hr(fg="yellow")

                click.secho(
                    "\nAs requested, I am sending details about this "
                    "error to Sentry, please report the following ID "
                    "when seeking support:"
                )

                exc_info = (type, value, traceback)
                event, hint = event_from_exception(
                    exc_info, client_options=sentry_client.options
                )
                event.setdefault("extra", {}).update(
                    {
                        "settings": as_dict(settings_diff),
                        "working_dir": os.getcwd(),
                    }
                )
                error_id = sentry_client.capture_event(event, hint=hint)
                click.secho("\n    {}\n".format(error_id), fg="yellow")
开发者ID:GaretJax,项目名称:lancet,代码行数:33,代码来源:cli.py


示例10: run

    def run(self):
        try:
            os.chdir(os.path.join("/var/openpanel/conf/staging", self.modname))
        
            self.req = self.getrequest()
        
            if self.req.command == "getconfig":
                self.sendresult(0, "OK", extra=self.getconfig())
                return
            
            if self.req.command == "updateok":
            	if self.updateok(self.fulltree["OpenCORE:Session"]["currentversion"]):
            		self.sendresult(0, "OK")
            	else:
            		self.sendresult(error.ERR_MODULE_UPDATE, "Cannot update")

            workerclass = self.getworkerclass(self.req.classid)
            wrapper = modulecallwrapper(workerclass, self.req)
            worker = getattr(wrapper, self.req.command)
            result = worker()
            self.sendresult(0, "OK", result)
        except:
            try:
                self.sendresult(error.ERR_MODULE_FAILURE, ''.join(traceback.format_exception(*sys.exc_info())))
            except:
                sys.__excepthook__(*sys.exc_info())
开发者ID:CloudVPS,项目名称:openpanel-opencore,代码行数:26,代码来源:modapi.py


示例11: excepthook

 def excepthook(type, value, trace):
     try:
         #            auto.press('alt')
         pass
     except:
         pass
     sys.__excepthook__(type, value, trace)
开发者ID:625781186,项目名称:first-test,代码行数:7,代码来源:function.py


示例12: unhandled_exception_handler

def unhandled_exception_handler(exc_type, exc_value, exc_traceback):
    if current_thread().name != 'MainThread':
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    exception_info = {}

    frame = wx.GetApp().GetTopWindow()

    #exception_info['version'] = wx.GetApp.Version

    exception_info['traceback'] = ''.join(traceback.format_exception(
            exc_type, exc_value, exc_traceback))

    exception_info['config'] = pprint.pformat(config)
    exception_info['flamepath'] = pprint.pformat(
            getattr(frame, 'flamepath', '<not set>'))

    exception_info['platform'] = sys.platform

    exception_info['UserParametersDir'] = wx.GetApp().UserParametersDir
    exception_info['RendersDir'] = wx.GetApp().RendersDir
    exception_info['UserScriptsDir'] = wx.GetApp().UserScriptsDir
    exception_info['ConfigDir'] = wx.GetApp().ConfigDir
    exception_info['Frozen'] = wx.GetApp().Frozen
    exception_info['AppBaseDir'] = wx.GetApp().AppBaseDir
    exception_info['IconsDir'] = wx.GetApp().IconsDir

    msg = """Error:
%(traceback)s

Platform: %(platform)s


Config: 
%(config)s

Flame Path:
%(flamepath)s

UserParametersDir: %(UserParametersDir)s
RendersDir: %(RendersDir)s
UserScriptsDir: %(UserScriptsDir)s
ConfigDir: %(ConfigDir)s
Frozen: %(Frozen)s
AppBaseDir: %(AppBaseDir)s
IconsDir: %(IconsDir)s
""" % exception_info

    print msg

    dlg = ExceptionDialog(frame, exc_type, exc_value, exception_info, msg)
    rv = dlg.ShowModal()
    dlg.Destroy()

    # Pass it on to python to crash or not
    sys.__excepthook__(exc_type, exc_value, exc_traceback)

    if rv == wx.ID_EXIT:
        sys.exit(1)
开发者ID:OpenMediaLab,项目名称:music2picture,代码行数:60,代码来源:exceptiondlg.py


示例13: run

def run(func, *args, **kwargs):
    """pdb hook: invokes pdb on exceptions in python.

    The function func is called, with arguments args and
    kwargs=kwargs.  If this func raises an exception, pdb is invoked
    on that frame.  Upon exit from pdb, return to python normally."""
    # save history
    old_hist = _get_history()
    old_hist_start = readline.get_current_history_length()+1

    try:
        return func(*args, **kwargs)
    except Exception as e:
        _add_history(_run_history)


        t, value, tb = sys.exc_info()
        sys.__excepthook__(t, value, tb)
        frame = sys.exc_info()[2]
        #tb = e.tb_frame
        pdb.post_mortem(tb)
        del frame   # the docs warn to avoid circular references.
        del t, value, tb

        _run_history[:] = _get_history(first=old_hist_start)
    readline.clear_history()
    _restore_history(old_hist)
    print old_hist
开发者ID:CxAalto,项目名称:verkko,代码行数:28,代码来源:pdbtb.py


示例14: uncaught_excepthook

def uncaught_excepthook(*args):
    sys.__excepthook__(*args)
    if __debug__:
        from pprint import pprint
        from types import BuiltinFunctionType, ClassType, ModuleType, TypeType
        tb = sys.last_traceback
        while tb.tb_next: tb = tb.tb_next
        print('\nDumping locals() ...')
        pprint({k:v for k,v in tb.tb_frame.f_locals.items()
                    if not k.startswith('_') and
                       not isinstance(v, (BuiltinFunctionType,
                                          ClassType, ModuleType, TypeType))})
        if sys.stdin.isatty() and (sys.stdout.isatty() or sys.stderr.isatty()):
            try:
                import ipdb as pdb  # try to import the IPython debugger
            except ImportError:
                import pdb as pdb
            print('\nStarting interactive debug prompt ...')
            pdb.pm()
    else:
        import traceback
        title = _('Unexpected error')
        msg = _('Debian Plymouth Manager has failed with the following unexpected error.\nPlease submit a bug report!')
        msg = "<b>{}</b>\n\n<tt>{}</tt>".format(msg, '\n'.join(traceback.format_exception(*args)))
        showMsg(title, msg)
    sys.exit(1)
开发者ID:SolydXK,项目名称:debian-plymouth-manager,代码行数:26,代码来源:main.py


示例15: myexcepthook

def myexcepthook(exctype, value, traceback):
    if exctype == KeyboardInterrupt:
        socket.close()
        exi()
        print "Handler code goes here"
    else:
        sys.__excepthook__(exctype, value, traceback)
开发者ID:born2net,项目名称:raspberry,代码行数:7,代码来源:socketPython.py


示例16: handle_unhandled_exceptions

def handle_unhandled_exceptions(exception_type, exception_value, exception_traceback):
    if not issubclass(exception_type, KeyboardInterrupt):
        if issubclass(exception_type, xapi.XenAPIException):
            info("Returned exception to XAPI", exc_info=(exception_type, exception_value, exception_traceback))
        else:
            error("Unhandled exception", exc_info=(exception_type, exception_value, exception_traceback))
    sys.__excepthook__(exception_type, exception_value, exception_traceback)
开发者ID:simonjbeaumont,项目名称:xapi-storage,代码行数:7,代码来源:log.py


示例17: _hook

def _hook(type_, value, tback):
    """Exception hook callback."""
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tback)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tback)

        # Dirty hack because Py27 doesn't chain exceptions
        if value.args:
            tb2 = value.args[-1]
            if isinstance(tb2, type(tback)):
                ex = value.args[-2]
                print >>sys.stderr, '{}Caused by{} '.format(
                    ansi('1;35m'), ansi('0m')),
                traceback.print_exception(type_(ex), ex, tb2)

            print
        # ...then start the debugger in post-mortem mode.
        # pdb.pm() # deprecated
        pdb.post_mortem(tback)  # more "modern"
开发者ID:ANZ-bank,项目名称:Sysl,代码行数:25,代码来源:debug.py


示例18: morse_excepthook

def morse_excepthook(*args, **kwargs):
    logger.error("[ERROR][MORSE] Uncaught exception, quit Blender.", exc_info = tuple(args))
    # call default python exception hook
    # on Ubuntu/Python3.4 sys.excepthook is overriden by `apport_excepthook`
    sys.__excepthook__(*args, **kwargs)
    import os
    os._exit(-1)
开发者ID:hawesie,项目名称:morse,代码行数:7,代码来源:main.py


示例19: uncaught_excepthook

def uncaught_excepthook(*args):
    sys.__excepthook__(*args)
    if __debug__:
        from pprint import pprint
        from types import BuiltinFunctionType, ClassType, ModuleType, TypeType
        tb = sys.last_traceback
        while tb.tb_next: tb = tb.tb_next
        print(('\nDumping locals() ...'))
        pprint({k:v for k,v in tb.tb_frame.f_locals.items()
                    if not k.startswith('_') and
                       not isinstance(v, (BuiltinFunctionType,
                                          ClassType, ModuleType, TypeType))})
        if sys.stdin.isatty() and (sys.stdout.isatty() or sys.stderr.isatty()):
            can_debug = False
            try:
                import ipdb as pdb  # try to import the IPython debugger
                can_debug = True
            except ImportError:
                try:
                    import pdb as pdb
                    can_debug = True
                except ImportError:
                    pass

            if can_debug:
                print(('\nStarting interactive debug prompt ...'))
                pdb.pm()
    else:
        import traceback
        details = '\n'.join(traceback.format_exception(*args)).replace('<', '').replace('>', '')
        title = 'Unexpected error'
        msg = 'The installer has failed with the following unexpected error. Please submit a bug report!'
        ErrorDialog(title, "<b>%s</b>" % msg, "<tt>%s</tt>" % details, None, True, 'live-installer-3')

    sys.exit(1)
开发者ID:SolydXK,项目名称:live-installer-3,代码行数:35,代码来源:main.py


示例20: log_exception

def log_exception(exc_type, exc_value, exc_traceback):
    # http://stackoverflow.com/a/16993115/2954547
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
    raise exc_type(exc_value).with_traceback(exc_traceback)
开发者ID:greg-rocketrip,项目名称:words_to_number,代码行数:7,代码来源:words_to_number.py



注:本文中的sys.__excepthook__函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sys._clear_type_cache函数代码示例发布时间:2022-05-27
下一篇:
Python exception.record_exception函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap