我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用sys.excepthook()。
def _log_all_uncaught_exceptions(exc_type, exc_value, exc_traceback): """Log all uncaught exceptions in non-interactive mode. All python exceptions are handled by function, stored in ``sys.excepthook.`` By rewriting the default implementation, we can modify handling of all uncaught exceptions. Warning: modified behaviour (logging of all uncaught exceptions) applies only when runing in non-interactive mode. """ # ignore KeyboardInterrupt if not issubclass(exc_type, KeyboardInterrupt): ROOT_LOGGER.error("", exc_info=(exc_type, exc_value, exc_traceback)) sys.__excepthook__(exc_type, exc_value, exc_traceback) return # Rewrite the default implementation os sys.excepthook to log all # uncaught exceptions:
def __init__( self, app ): self.app = app self.__log_widget = WbLogTextWidget( self.app ) self.__line = '' # Redirect the console IO to this panel sys.stdin = wb_platform_specific.getNullDevice().open( 'r' ) if self.app.stdIoRedirected(): sys.stdout = self sys.stderr = self sys.excepthook = self.excepthook # Redirect log to the Log panel self.widget_log_handler = WidgetLogHandler( self.app, self.__log_widget ) self.app.log.addHandler( self.widget_log_handler ) self.__session_log = open( str(wb_platform_specific.getLogFilename()) + '.session.log', 'w', buffering=1 )
def excepthook( self, type_, value, tb ): # emergency write self.__session_log.write( 'excepthook called\n' ) self.__session_log.flush() all_exception_lines = traceback.format_exception( type_, value, tb ) for line in all_exception_lines: self.__session_log.write( line ) self.__session_log.flush() # cannot use the GUI window now app is not sane self.app.log.removeHandler( self.widget_log_handler ) self.app.log.error( 'excepthook called' ) for line in all_exception_lines: self.app.log.error( line.replace( '\n', '' ) ) self.app.runInForeground( self.app.log.addHandler, (self.widget_log_handler,) ) self.app.runInForeground( self.app.log.error, ('Check log for traceback details',) )
def pre_arg_parse_except_hook(memory_handler, *args, **kwargs): """A simple wrapper around post_arg_parse_except_hook. The additional functionality provided by this wrapper is the memory handler will be flushed before Certbot exits. This allows us to write logging messages to a temporary file if we crashed before logging was fully configured. Since sys.excepthook isn't called on SystemExit exceptions, the memory handler will not be flushed in this case which prevents us from creating temporary log files when argparse exits because a command line argument was invalid or -h, --help, or --version was provided on the command line. :param MemoryHandler memory_handler: memory handler to flush :param tuple args: args for post_arg_parse_except_hook :param dict kwargs: kwargs for post_arg_parse_except_hook """ try: post_arg_parse_except_hook(*args, **kwargs) finally: # flush() is called here so messages logged during # post_arg_parse_except_hook are also flushed. memory_handler.flush(force=True)
def __init__(self, user_data_control): super().__init__() sys.excepthook = self._displayError self._udc = user_data_control self.check = QPixmap("res/check.png") self.cancel = QPixmap("res/cancel.png") self.setGeometry(500, 500, 500, 465) self.init_ui() self.init_window() self.init_user_data() self.setWindowTitle(self.APP_TITLE) self.setWindowIcon(QIcon('res/rabbit.png')) center(self) self.show() # PyQt Error Handling
def octario_excepthook(exc_type, exc_value, exc_traceback): """exception hook that sends OctarioException to log and other exceptions to stderr (default excepthook) """ from octario.lib.exceptions import OctarioException # sends full exception with trace to log if not isinstance(exc_value, OctarioException): return sys.__excepthook__(exc_type, exc_value, exc_traceback) if LOG.getEffectiveLevel() <= logging.DEBUG: formated_exception = "".join( traceback.format_exception(exc_type, exc_value, exc_traceback)) LOG.error(formated_exception + exc_value.message) else: LOG.error(exc_value.message)
def boto_except_hook(debugger_flag, debug_flag): def excepthook(typ, value, tb): if typ is bdb.BdbQuit: sys.exit(1) sys.excepthook = sys.__excepthook__ if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty(): if debugger.__name__ == 'epdb': debugger.post_mortem(tb, typ, value) else: debugger.post_mortem(tb) elif debug_flag: print(traceback.print_tb(tb)) sys.exit(1) else: print(value) sys.exit(1) return excepthook
def process_standard_options(self, options, args, d): if hasattr(options, 'help_filters') and options.help_filters: print('Available filters:') for filter in self.Filters: print('%s\t%s' % (filter.name, filter.doc)) sys.exit(0) if options.debug: self.args['debug'] = 2 if options.url: self.args['url'] = options.url if options.region: self.args['region'] = options.region if options.access_key_id: self.args['aws_access_key_id'] = options.access_key_id if options.secret_key: self.args['aws_secret_access_key'] = options.secret_key if options.version: # TODO - Where should the version # come from? print('version x.xx') exit(0) sys.excepthook = boto_except_hook(options.debugger, options.debug)
def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(wrap=six.PY3) doc = usage.get_primary_command_usage() allow_subcommands = '<command>' in doc args = docopt(doc, version=settings.version, options_first=allow_subcommands) if sys.excepthook is sys.__excepthook__: sys.excepthook = log.excepthook try: log.enable_logging(log.get_log_level(args)) default_args = sys.argv[2 if args.get('<command>') else 1:] if (args.get('<command>') == 'help' and None not in settings.subcommands): subcommand = next(iter(args.get('<args>', default_args)), None) return usage.get_help_usage(subcommand) argv = [args.get('<command>')] + args.get('<args>', default_args) return _run_command(argv) except exc.InvalidCliValueError as e: return str(e)
def init_traceback_handlers(self, custom_exceptions): # Syntax error handler. self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) # The interactive one is initialized with an offset, meaning we always # want to remove the topmost item in the traceback, which is our own # internal code. Valid modes: ['Plain','Context','Verbose'] self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', color_scheme='NoColor', tb_offset = 1, check_cache=check_linecache_ipython, debugger_cls=self.debugger_cls, parent=self) # The instance will store a pointer to the system-wide exception hook, # so that runtime code (such as magics) can access it. This is because # during the read-eval loop, it may get temporarily overwritten. self.sys_excepthook = sys.excepthook # and add any custom exception handlers the user may have specified self.set_custom_exc(*custom_exceptions) # Set the exception mode self.InteractiveTB.set_mode(mode=self.xmode)
def excepthook(self, etype, value, tb): """One more defense for GUI apps that call sys.excepthook. GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their mainloop. This is a bother for IPython which excepts to catch all of the program exceptions with a try: except: statement. Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes. This hook should be used sparingly, only in places which are not likely to be true IPython errors. """ self.showtraceback((etype, value, tb), tb_offset=0)
def __init__(self, **kw): if kw.get('user_global_ns', None) is not None: raise DeprecationWarning( "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") clid = kw.pop('_init_location_id', None) if not clid: frame = sys._getframe(1) clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) self._init_location_id = clid super(InteractiveShellEmbed,self).__init__(**kw) # don't use the ipython crash handler so that user exceptions aren't # trapped sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, mode=self.xmode, call_pdb=self.pdb)
def enable_pyqt_exception_hook(): """Enable the PyQt exception handling hook for PyQt versions larger than 5.5. If this is not enabled, exceptions will be handled silently and will not be printed to the user. This makes it harder to solve the issue. """ if QtCore.QT_VERSION >= 0x50501: old_stdout = sys.stdout old_stderr = sys.stderr def excepthook(type_, value, traceback_): sys.stdout = old_stdout sys.stderr = old_stderr traceback.print_exception(type_, value, traceback_) QtCore.qFatal('') sys.excepthook = excepthook
def test_perform_changes_dpkg_error_retains_excepthook(self): """ We install a special excepthook when preforming package operations, to prevent Apport from generating crash reports when dpkg returns a failure. It's only installed when doing the actual package operation, so the original excepthook is there after the perform_changes() method returns. """ old_excepthook = sys.excepthook self._add_system_package("foo") self.facade.reload_channels() foo = self.facade.get_packages_by_name("foo")[0] self.facade.mark_remove(foo) with self.assertRaises(TransactionError): self.facade.perform_changes() self.assertIs(old_excepthook, sys.excepthook)
def set_cli_except_hook(): def recommend(possible_solutions): logger.info('Possible solutions:') for solution in possible_solutions: logger.info(' - {0}'.format(solution)) def new_excepthook(tpe, value, trace): if env.logging.is_high_verbose_level(): # log error including traceback logger.error(get_exception_as_string(tpe, value, trace)) else: # write the full error to the log file with open(env.logging.log_file, 'a') as log_file: traceback.print_exception( etype=tpe, value=value, tb=trace, file=log_file) # print only the error message print value if hasattr(value, 'possible_solutions'): recommend(getattr(value, 'possible_solutions')) sys.excepthook = new_excepthook
def __call__(self, parser, namespace, values, option_string = None): # If we recognize one of the arguments on the command line as indicating a # different mechanism for handling tracebacks, we attach one of those handlers # and remove the argument from sys.argv. # if self.dest == "paste": sys.excepthook = paste_traceback mylog.debug("Enabling traceback pasting") elif self.dest == "paste-detailed": sys.excepthook = paste_traceback_detailed mylog.debug("Enabling detailed traceback pasting") elif self.dest == "detailed": import cgitb cgitb.enable(format="text") mylog.debug("Enabling detailed traceback reporting") elif self.dest == "rpdb": sys.excepthook = rpdb.rpdb_excepthook mylog.debug("Enabling remote debugging")
def main(): """Main function.""" sys.excepthook = error_handler try: signal.signal(signal.SIGINT, sigint_handler) except ValueError: print('Warning: couldn\'t start SIGINT (ctrl-c) handler.') QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) app.setStyleSheet(stylesheets[0]) window = DiscordWindow() timer = QTimer() timer.start(20) # let interpreter run every 550ms timer.timeout.connect(lambda: None) window.show() window.raise_() window.setWindowState(window.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) window.activateWindow() # mac... app.aboutToQuit.connect(lambda: quit_cleanup(window)) exc = app.exec_() return exc
def prehook(self, emu, op, starteip): if not self.onceop.get(starteip): self.onceop[starteip] = True for i, o in enumerate(op.opers): if o.isDeref(): discrete = o.isDiscrete() operva = o.getOperAddr(op, emu) # keep track of the max here, but save it for later too... stackoff = emu.getStackOffset(operva) if stackoff is not None: # py 2->3 specific if stackoff >= 0: self.stackmax = max(self.stackmax, stackoff) self.operrefs.append((starteip, i, operva, o.tsize, stackoff, discrete)) if op.iflags & BRANCH_FLAGS: oper = op.opers[0] if oper.isDeref() or oper.isReg(): for cb in self._dynamic_branch_handlers: try: cb(self, emu, op, starteip) except: sys.excepthook(*sys.exc_info())
def except_hook(exception_type, value, tb): if show_messagebox_on_exception: focused_widget = QApplication.focusWidget() if focused_widget: if exception_type == type_defs.GDBInitializeException: QMessageBox.information(focused_widget, "Error", "GDB isn't initialized yet") elif exception_type == type_defs.InferiorRunningException: error_dialog = InputDialogForm(item_list=[("Process is running" + "\nPress " + break_hotkey + " to stop process" + "\n\nGo to settings->General to disable this dialog",)]) error_dialog.exec_() traceback.print_exception(exception_type, value, tb) # From version 5.5 and onwards, PyQT calls qFatal() when an exception has been encountered # So, we must override sys.excepthook to avoid calling of qFatal()
def _run_handlers(): """_run_handlers() Run registered handlers. They run in the reverse order of which they were registered. If a handler raises an exception, it will be printed but nothing else happens, i.e. other handlers will be run. """ context.clear() for _ident, (func, args, kwargs, ctx) in \ sorted(_handlers.items(), reverse = True): try: with context.local(**ctx): func(*args, **kwargs) except SystemExit: pass except: # extract the current exception and rewind the traceback to where it # originated typ, val, tb = sys.exc_info() traceback.print_exception(typ, val, tb.tb_next) # we rely on the existing excepthook to print exceptions
def failed(self): # check, if the reason was a ConfigureDryRunError or a # ConfigureCacheError and if yes, reraise the exception exc_type = self.exc_info()[0] if issubclass(exc_type, SConfError): raise elif issubclass(exc_type, SCons.Errors.BuildError): # we ignore Build Errors (occurs, when a test doesn't pass) # Clear the exception to prevent the contained traceback # to build a reference cycle. self.exc_clear() else: self.display('Caught exception while building "%s":\n' % self.targets[0]) sys.excepthook(*self.exc_info()) return SCons.Taskmaster.Task.failed(self)
def configure_logging(self, level=logging.INFO, debug=False): """ Configures the basic logging for the experiment. This creates a handler for logging to the console, sets it at the appropriate level (info by default unless overridden in the config file or by the debug flag) and creates the default formatting for log messages. """ if debug is True: self.log_level = logging.DEBUG else: self.log_level = level sys.excepthook = _log_except_hook # send uncaught exceptions to file logging.basicConfig( level=self.log_level, format='"%(asctime)s","%(levelname)s","%(message)s"' ) # Make sure that the stream handler has the requested log level. root_logger = logging.getLogger() for handler in root_logger.handlers: if isinstance(handler, logging.StreamHandler): handler.setLevel(self.log_level)
def _set_pm_excepthook(handle_exceptions_dict=None): ''' Should be called to register the excepthook to be used. It's only useful for uncaught exceptions. I.e.: exceptions that go up to the excepthook. @param handle_exceptions: dict(exception -> ExceptionBreakpoint) The exceptions that should be handled. ''' global _handle_exceptions global _original_excepthook if sys.excepthook != _excepthook: #Only keep the original if it's not our own _excepthook (if called many times). _original_excepthook = sys.excepthook _handle_exceptions = handle_exceptions_dict sys.excepthook = _excepthook
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.""" #Override for avoid using sys.excepthook PY-12600 type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value list = traceback.format_exception_only(type, value) sys.stderr.write(''.join(list))
def showtraceback(self): """Display the exception that just occurred.""" #Override for avoid using sys.excepthook PY-12600 try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(type, value)) finally: tblist = tb = None sys.stderr.write(''.join(lines))
def exit_by_exception(): class SignalException(BaseException): pass def signal_fork(signum, stack_frame): log.info('Received signal %d, procuring hariki', signum) raise SignalException(signum) def excepthook(exc_type, exc_value, exc_trace): if exc_type is SignalException: sys.exit(1) else: sys.__excepthook__(exc_type, exc_value, exc_trace) sys.excepthook = excepthook signal.signal(signal.SIGINT, signal_fork) signal.signal(signal.SIGTERM, signal_fork)
def prototype(*outer_args,**outer_kwargs): """ Verify that a method is called with a valid data type value. The datatype of a parameter must be a one of the type defined in types package. """ def decorator(fn): def decorated(*args,**kwargs): #do_something(*outer_args,**outer_kwargs) if len(outer_args)!=len(args): sys.excepthook = __exceptionHandler__ raise Exception("Invalid Number of " "arguments in function call") for [typ, var] in zip(outer_args, args): if ( isinstance(var, typ)): pass else: sys.excepthook = __exceptionHandler__ raise Exception("Invalid Type") return fn(*args,**kwargs) return decorated return decorator
def ovrprototype(*outer_args,**outer_kwargs): """ Verify that a method is called with a valid data type value. The datatype of a parameter must be a list of type defined in package types. """ def decorator(fn): def decorated(*args,**kwargs): #do_something(*outer_args,**outer_kwargs) if len(outer_args)!=len(args): sys.excepthook = __exceptionHandler__ raise Exception("Invalid Number of " "arguments in function call") for [typ, var] in zip(outer_args, args): matched = False for i_typ in typ: if ( isinstance(var, i_typ)): matched = True break if matched == False: sys.excepthook = __exceptionHandler__ raise Exception("Invalid Type") return fn(*args,**kwargs) return decorated return decorator
def _exitfunc(cls): # At shutdown invoke finalizers for which atexit is true. # This is called once all other non-daemonic threads have been # joined. reenable_gc = False try: if cls._registry: import gc if gc.isenabled(): reenable_gc = True gc.disable() pending = None while True: if pending is None or finalize._dirty: pending = cls._select_for_exit() finalize._dirty = False if not pending: break f = pending.pop() try: # gc is disabled, so (assuming no daemonic # threads) the following is the only line in # this function which might trigger creation # of a new finalizer f() except Exception: sys.excepthook(*sys.exc_info()) assert f not in cls._registry finally: # prevent any more finalizers from executing during shutdown finalize._shutdown = True if reenable_gc: gc.enable()
def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize except ImportError: pass except Exception: if sys.flags.verbose: sys.excepthook(*sys.exc_info()) else: print >>sys.stderr, \ "'import sitecustomize' failed; use -v for traceback"
def execusercustomize(): """Run custom user specific code, if available.""" try: import usercustomize except ImportError: pass except Exception: if sys.flags.verbose: sys.excepthook(*sys.exc_info()) else: print>>sys.stderr, \ "'import usercustomize' failed; use -v for traceback"
def enable(display=1, logdir=None, context=5, format="html"): """Install an exception handler that formats tracebacks as HTML. The optional argument 'display' can be set to 0 to suppress sending the traceback to the browser, and 'logdir' can be set to a directory to cause tracebacks to be written to files there.""" sys.excepthook = Hook(display=display, logdir=logdir, context=context, format=format)
def excepthook(*exception_info): logger.error('unexpected error',exc_info=exception_info) message = QtGui.QMessageBox(None) message.setWindowTitle(QtGui.qApp.applicationName()) message.setIcon(QtGui.QMessageBox.Critical) message.setText('An unexpected error occurred.') message.setDetailedText(logging_stream.getvalue()) message.setStandardButtons(QtGui.QMessageBox.Ok) message.setDefaultButton(QtGui.QMessageBox.Ok) message.exec_() QtGui.qApp.exit()
def init_logger(): logging.basicConfig(filename="pjf_{0}.log".format(time.strftime("%d_%m_%Y")), level=PYJFUZZ_LOGLEVEL) logger = logging.getLogger(__name__) sys.tracebacklimit = 10 def handle_exception(exc_type, exc_value, exc_traceback): 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)) sys.__excepthook__(exc_type, exc_value, None) return sys.excepthook = handle_exception return logger
def setup(level=logging.WARNING, outputs=[output.STDERR], program_name=None, capture_warnings=True): """Setup Python logging. This will setup basic handlers for Python logging. :param level: Root log level. :param outputs: Iterable of outputs to log to. :param program_name: The name of the program. Auto-detected if not set. :param capture_warnings: Capture warnings from the `warnings' module. """ root_logger = logging.getLogger(None) # Remove all handlers for handler in list(root_logger.handlers): root_logger.removeHandler(handler) # Add configured handlers for out in outputs: if isinstance(out, str): out = output.preconfigured.get(out) if out is None: raise RuntimeError("Output {} is not available".format(out)) out.add_to_logger(root_logger) root_logger.setLevel(level) program_logger = logging.getLogger(program_name) def logging_excepthook(exc_type, value, tb): program_logger.critical( "".join(traceback.format_exception(exc_type, value, tb))) sys.excepthook = logging_excepthook if capture_warnings: logging.captureWarnings(True)
def crashtest(): global allWidgets try: gc.disable() actions = [ createWidget, #setParent, forgetWidget, showWidget, processEvents, #raiseException, #addReference, ] thread = WorkThread() thread.start() while True: try: action = randItem(actions) action() print('[%d widgets alive, %d zombie]' % (len(allWidgets), len(allWidgets) - len(widgets))) except KeyboardInterrupt: print("Caught interrupt; send another to exit.") try: for i in range(100): QtTest.QTest.qWait(100) except KeyboardInterrupt: thread.terminate() break except: sys.excepthook(*sys.exc_info()) finally: gc.enable()
def printException(exctype, value, traceback): """Print an exception with its full traceback. Set `sys.excepthook = printException` to ensure that exceptions caught inside Qt signal handlers are printed with their full stack trace. """ print(''.join(formatException(exctype, value, traceback, skip=1)))
def implements(self, interface=None): ## this just makes it easy for us to detect whether an ExceptionHook is already installed. if interface is None: return ['ExceptionHandler'] else: return interface == 'ExceptionHandler' ## replace built-in excepthook only if this has not already been done
def eventLoop(self): while True: try: self.processRequests() # exception raised when the loop should exit time.sleep(0.01) except ClosedError: break except: print("Error occurred in forked event loop:") sys.excepthook(*sys.exc_info()) sys.exit(0)
def __exit__(self, *exc_info): if self.proc is not None: ## worker exceptOccurred = exc_info[0] is not None ## hit an exception during processing. try: if exceptOccurred: sys.excepthook(*exc_info) finally: #print os.getpid(), 'exit' os._exit(1 if exceptOccurred else 0) else: ## parent if self.showProgress: self.progressDlg.__exit__(None, None, None)
def run(self): global path, version, initVersion, forcedVersion, installVersion name = self.config_vars['dist_name'] print(name) path = os.path.join(self.install_libbase, 'NeoAnalysis') if os.path.exists(path): raise Exception("It appears another version of %s is already " "installed at %s; remove this before installing." % (name, path)) print("Installing to %s" % path) rval = install.install.run(self) # If the version in __init__ is different from the automatically-generated # version string, then we will update __init__ in the install directory if initVersion == version: return rval try: initfile = os.path.join(path, '__init__.py') data = open(initfile, 'r').read() open(initfile, 'w').write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data)) installVersion = version except: sys.stderr.write("Warning: Error occurred while setting version string in build path. " "Installation will use the original version string " "%s instead.\n" % (initVersion) ) if forcedVersion: raise installVersion = initVersion sys.excepthook(*sys.exc_info()) return rval
def exceptionhook(exception_type, exception, traceback, default_hook = sys.excepthook): if 'Toehold' in exception_type.__name__ : print("{}: {}".format('RuntimeError', exception.message)) else: default_hook(exception_type, exception, traceback)