Python sys.excepthook() Examples

The following are code examples for showing how to use sys.excepthook(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: where   Author: kartverket   File: util.py    MIT License 7 votes vote down vote up
def no_traceback(func):
    """Decorator for turning off traceback, instead printing a simple error message

    Use the option --show_tb to show the traceback anyway.
    """
    if check_options("-T", "--showtb"):
        return func

    def no_traceback_hook(_not_used_1, value, _not_used_2):
        """Only prints the error message, no traceback."""
        log.error(str(value))

    @functools.wraps(func)
    def _no_traceback(*args, **kwargs):
        remember_excepthook = sys.excepthook
        sys.excepthook = no_traceback_hook
        values = func(*args, **kwargs)
        sys.excepthook = remember_excepthook
        return values

    return _no_traceback 
Example 2
Project: synspy   Author: informatics-isi-edu   File: __main__.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    sys.excepthook = excepthook

    QApplication.setDesktopSettingsAware(False)
    QApplication.setStyle(QStyleFactory.create("Fusion"))
    app = QApplication(sys.argv)
    app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    app.setWindowIcon(QIcon(":/images/synapse.png"))
    cli = BaseCLI("Synapse Viewer Launcher",
                  "For more information see: https://github.com/informatics-isi-edu/synspy", synspy_version)
    cli.remove_options(["--credential-file"])
    args = cli.parse_cli()
    mainWindow = mw.MainWindow(args.config_file)
    mainWindow.show()
    ret = app.exec_()
    return ret 
Example 3
Project: study   Author: program-in-chinese   File: 解释器.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def showtraceback(self):
        sys.last_type, sys.last_value, 回溯信息 = 运行信息 = sys.exc_info()
        sys.last_traceback = 回溯信息
        try:
            行 = traceback.format_exception(运行信息[0], 运行信息[1], 回溯信息.tb_next)
            汉化行 = []
            if sys.excepthook is sys.__excepthook__:
                for 某行 in 行:
                    汉化行.append(self.中文化(某行))
                self.write(''.join(汉化行))
            else:
                # If someone has set sys.excepthook, we let that take precedence
                # over self.write
                sys.excepthook(运行信息[0], 运行信息[1], 回溯信息)
        finally:
            回溯信息 = 运行信息 = None

    # 参考: https://docs.python.org/3/library/re.html#re.sub 
Example 4
Project: Repobot   Author: Desgard   File: embed.py    MIT License 6 votes vote down vote up
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) 
Example 5
Project: Repobot   Author: Desgard   File: interactiveshell.py    MIT License 6 votes vote down vote up
def init_traceback_handlers(self, custom_exceptions):
        # Syntax error handler.
        self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')

        # 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)

        # 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) 
Example 6
Project: Repobot   Author: Desgard   File: interactiveshell.py    MIT License 6 votes vote down vote up
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) 
Example 7
Project: iv   Author: kovidgoyal   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, files):
        QMainWindow.__init__(self)
        sys.excepthook = self.excepthook
        self.view = View(self)
        self.view.set_title.connect(self.set_title)
        self.view.refresh_all.connect(self.refresh_all)
        self.setCentralWidget(self.view)
        self.files = files
        self.directories = {os.path.dirname(f['path']) for f in files.values()}
        self.file_watcher = QFileSystemWatcher([f['path'] for f in files.values()] + list(self.directories), self)
        self.file_watcher.fileChanged.connect(self.file_changed, type=Qt.QueuedConnection)
        self.file_watcher.directoryChanged.connect(self.directory_changed, type=Qt.QueuedConnection)
        self.changed_files = set()
        self.changed_dirs = set()
        self.debounce_files, self.debounce_dirs = QTimer(), QTimer()
        for t in self.debounce_files, self.debounce_dirs:
            t.setInterval(1000), t.setSingleShot(True)
        self.debounce_files.timeout.connect(self.do_file_changed)
        self.debounce_dirs.timeout.connect(self.do_dir_changed)
        self.set_title(None) 
Example 8
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevd_console.py    MIT License 6 votes vote down vote up
def runcode(self, code):
        """Execute a code object.

        When an exception occurs, self.showtraceback() is called to
        display a traceback.  All exceptions are caught except
        SystemExit, which is reraised.

        A note about KeyboardInterrupt: this exception may occur
        elsewhere in this code, and may not always be caught.  The
        caller should be prepared to deal with it.

        """
        try:
            Exec(code, self.frame.f_globals, self.frame.f_locals)
            pydevd_save_locals.save_locals(self.frame)
        except SystemExit:
            raise
        except:
            # In case sys.excepthook called, use original excepthook #PyDev-877: Debug console freezes with Python 3.5+
            # (showtraceback does it on python 3.5 onwards)
            sys.excepthook = sys.__excepthook__
            try:
                self.showtraceback()
            finally:
                sys.__excepthook__ = sys.excepthook 
Example 9
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole.py    MIT License 6 votes vote down vote up
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)) 
Example 10
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole.py    MIT License 6 votes vote down vote up
def showtraceback(self, *args, **kwargs):
        """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)) 
Example 11
Project: Dolphin-Updater   Author: nbear3   File: dolphinapp.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: code.py    GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
        sys.last_traceback = last_tb
        try:
            lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
            if sys.excepthook is sys.__excepthook__:
                self.write(''.join(lines))
            else:
                # If someone has set sys.excepthook, we let that take precedence
                # over self.write
                sys.excepthook(ei[0], ei[1], last_tb)
        finally:
            last_tb = ei = None 
Example 13
Project: NiujiaoDebugger   Author: MrSrc   File: test_concurrent_futures.py    GNU General Public License v3.0 6 votes vote down vote up
def test_traceback(self):
        # We want ensure that the traceback from the child process is
        # contained in the traceback raised in the main process.
        future = self.executor.submit(self._test_traceback)
        with self.assertRaises(Exception) as cm:
            future.result()

        exc = cm.exception
        self.assertIs(type(exc), RuntimeError)
        self.assertEqual(exc.args, (123,))
        cause = exc.__cause__
        self.assertIs(type(cause), futures.process._RemoteTraceback)
        self.assertIn('raise RuntimeError(123) # some comment', cause.tb)

        with test.support.captured_stderr() as f1:
            try:
                raise exc
            except RuntimeError:
                sys.excepthook(*sys.exc_info())
        self.assertIn('raise RuntimeError(123) # some comment',
                      f1.getvalue()) 
Example 14
Project: NiujiaoDebugger   Author: MrSrc   File: resource_sharer.py    GNU General Public License v3.0 6 votes vote down vote up
def _serve(self):
        if hasattr(signal, 'pthread_sigmask'):
            signal.pthread_sigmask(signal.SIG_BLOCK, range(1, signal.NSIG))
        while 1:
            try:
                with self._listener.accept() as conn:
                    msg = conn.recv()
                    if msg is None:
                        break
                    key, destination_pid = msg
                    send, close = self._cache.pop(key)
                    try:
                        send(conn, destination_pid)
                    finally:
                        close()
            except:
                if not util.is_exiting():
                    sys.excepthook(*sys.exc_info()) 
Example 15
Project: NiujiaoDebugger   Author: MrSrc   File: site.py    GNU General Public License v3.0 6 votes vote down vote up
def execusercustomize():
    """Run custom user specific code, if available."""
    try:
        try:
            import usercustomize
        except ImportError as exc:
            if exc.name == 'usercustomize':
                pass
            else:
                raise
    except Exception as err:
        if sys.flags.verbose:
            sys.excepthook(*sys.exc_info())
        else:
            sys.stderr.write(
                "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
                "%s: %s\n" %
                (err.__class__.__name__, err)) 
Example 16
Project: cloudify-agent   Author: cloudify-cosmo   File: worker.py    Apache License 2.0 6 votes vote down vote up
def _setup_excepthook(daemon_name):
    # Setting a new exception hook to catch any exceptions
    # on agent startup and write them to a file. This file
    # is later read for querying if celery has started successfully.
    current_excepthook = sys.excepthook

    def new_excepthook(exception_type, value, the_traceback):
        # use the storage directory because the work directory might have
        # been created under a different user, in which case we don't have
        # permissions to write to it.
        storage = utils.internal.get_daemon_storage_dir()
        if not os.path.exists(storage):
            os.makedirs(storage)
        error_dump_path = os.path.join(
            utils.internal.get_daemon_storage_dir(),
            '{0}.err'.format(daemon_name))
        with open(error_dump_path, 'w') as f:
            f.write('Type: {0}\n'.format(exception_type))
            f.write('Value: {0}\n'.format(value))
            traceback.print_tb(the_traceback, file=f)
        current_excepthook(exception_type, value, the_traceback)

    sys.excepthook = new_excepthook 
Example 17
Project: Lyff   Author: akashlevy   File: awsqueryrequest.py    MIT License 6 votes vote down vote up
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 
Example 18
Project: Lyff   Author: akashlevy   File: awsqueryrequest.py    MIT License 6 votes vote down vote up
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) 
Example 19
Project: Nest   Author: ZhouYanzhao   File: cli.py    MIT License 6 votes vote down vote up
def hook_exceptions(self, logger: logging.RootLogger) -> None:
        """Format excetion traceback.
        
        Parameters:
            logger:
                The logger for logging exceptions.
        """

        def _hook(exc_type, value, exc_tb) -> None:
            nest_dir = os.path.dirname(os.path.abspath(__file__))
            traceback_str = ''
            idx = 0
            for file_name, line_number, func_name, text in traceback.extract_tb(exc_tb)[1:]:
                # skip Nest-related tracebacks to make it more readable
                if os.path.dirname(os.path.abspath(file_name)) == nest_dir:
                    continue
                idx += 1
                traceback_str += '\n  [%d] File "%s", line %d, in function "%s"\n    %s' % \
                    (idx, file_name, line_number, func_name, text)
            if traceback_str != '':
                traceback_str = 'Traceback: ' + traceback_str
            logger.critical('Exception occurred during resolving:\nType: %s\nMessage: %s\n%s' % \
                (exc_type.__name__, value, traceback_str))

        sys.excepthook = _hook 
Example 20
Project: incubator-spot   Author: apache   File: listener.py    Apache License 2.0 5 votes vote down vote up
def main():
    '''
        Main entry point for Spark Streaming Listener functionality.
    '''
    try: streaming_listener(**parse_args().__dict__)
    except SystemExit: raise
    except:
        sys.excepthook(*sys.exc_info())
        sys.exit(1) 
Example 21
Project: pyblish-win   Author: pyblish   File: cgitb.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 22
Project: pyblish-win   Author: pyblish   File: site.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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" 
Example 23
Project: pyblish-win   Author: pyblish   File: site.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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" 
Example 24
Project: RelayBot2.0   Author: nukeop   File: errors.py    GNU General Public License v3.0 5 votes vote down vote up
def set_exception_handler():
    sys.excepthook = exc_handler 
Example 25
Project: sic   Author: Yanixos   File: weakref.py    GNU General Public License v3.0 5 votes vote down vote up
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() 
Example 26
Project: reportengine   Author: NNPDF   File: app.py    GNU General Public License v2.0 5 votes vote down vote up
def excepthook(self, etype, evalue, tb):
        print("\n----\n")
        print(colors.color_exception(etype, evalue, tb), file=sys.stderr)
        print("----\n")

        fd,name = tempfile.mkstemp(prefix=self.name + '-crash-', text=True)
        with os.fdopen(fd, 'w') as f:
            traceback.print_exception(etype, evalue, tb, file=f)



        root_log.critical(self.critical_message, colors.t.blue(name)) 
Example 27
Project: reportengine   Author: NNPDF   File: app.py    GNU General Public License v2.0 5 votes vote down vote up
def init(self, cmdline=None):
        import faulthandler
        faulthandler.enable()
        args = self.get_commandline_arguments(cmdline)
        self.init_logging(args)
        sys.excepthook = self.excepthook
        try:
            self.environment = self.make_environment(args)
        except EnvironmentError_ as e:
            traceback_if_debug(e)
            log.error(e)
            sys.exit(1)
        self.init_style(args)
        self.init_providers(args)
        self.args = args 
Example 28
Project: lirpg   Author: Hwhitetooth   File: util.py    MIT License 5 votes vote down vote up
def install_mpi_excepthook():
    import sys
    from mpi4py import MPI
    old_hook = sys.excepthook

    def new_hook(a, b, c):
        old_hook(a, b, c)
        sys.stdout.flush()
        sys.stderr.flush()
        MPI.COMM_WORLD.Abort()
    sys.excepthook = new_hook 
Example 29
Project: HardRLWithYoutube   Author: MaxSobolMark   File: util.py    MIT License 5 votes vote down vote up
def install_mpi_excepthook():
    import sys
    from mpi4py import MPI
    old_hook = sys.excepthook

    def new_hook(a, b, c):
        old_hook(a, b, c)
        sys.stdout.flush()
        sys.stderr.flush()
        MPI.COMM_WORLD.Abort()
    sys.excepthook = new_hook 
Example 30
Project: synspy   Author: informatics-isi-edu   File: __main__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def excepthook(etype, value, tb):
    traceback.print_tb(tb)
    sys.stderr.write(format_exception(value))
    msg = QMessageBox()
    msg.setText(str(value))
    msg.setStandardButtons(QMessageBox.Close)
    msg.setWindowTitle("Unhandled Exception: %s" % etype.__name__)
    msg.setIcon(QMessageBox.Critical)
    msg.setDetailedText('\n'.join(traceback.format_exception(etype, value, tb)))
    msg.exec_() 
Example 31
Project: MyDotfiles   Author: Sup3r-Us3r   File: mem.py    GNU General Public License v3.0 5 votes vote down vote up
def std_exceptions(etype, value, tb):
    sys.excepthook = sys.__excepthook__
    if issubclass(etype, KeyboardInterrupt):
        pass
    elif issubclass(etype, IOError) and value.errno == errno.EPIPE:
        pass
    else:
        sys.__excepthook__(etype, value, tb) 
Example 32
Project: pywren-ibm-cloud   Author: pywren   File: ps_mem.py    Apache License 2.0 5 votes vote down vote up
def std_exceptions(etype, value, tb):
    sys.excepthook = sys.__excepthook__
    if issubclass(etype, KeyboardInterrupt):
        pass
    elif issubclass(etype, IOError) and value.errno == errno.EPIPE:
        pass
    else:
        sys.__excepthook__(etype, value, tb) 
Example 33
Project: AHSSpider   Author: yujunjiex   File: main_spider.py    MIT License 5 votes vote down vote up
def install_except_hook():
    """把未捕获的异常输入到logging"""
    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):  # ctrl+c不捕获
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return

        logger.error("{} Uncaught exception".format(threading.current_thread().name),
                     exc_info=(exc_type, exc_value, exc_traceback))

    sys.excepthook = handle_exception 
Example 34
Project: study   Author: program-in-chinese   File: 解释器.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        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
        if sys.excepthook is sys.__excepthook__:
            行 = traceback.format_exception_only(type, value)
            汉化行 = []
            for 某行 in 行:
                汉化行.append(self.中文化(某行))
            self.write(''.join(汉化行))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb)

    # 由InteractiveConsole.showtraceback源码改写 
Example 35
Project: Repobot   Author: Desgard   File: interactiveshell.py    MIT License 5 votes vote down vote up
def save_sys_module_state(self):
        """Save the state of hooks in the sys module.

        This has to be called after self.user_module is created.
        """
        self._orig_sys_module_state = {'stdin': sys.stdin,
                                       'stdout': sys.stdout,
                                       'stderr': sys.stderr,
                                       'excepthook': sys.excepthook}
        self._orig_sys_modules_main_name = self.user_module.__name__
        self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) 
Example 36
Project: Repobot   Author: Desgard   File: crashhandler.py    MIT License 5 votes vote down vote up
def crash_handler_lite(etype, evalue, tb):
    """a light excepthook, adding a small message to the usual traceback"""
    traceback.print_exception(etype, evalue, tb)
    
    from IPython.core.interactiveshell import InteractiveShell
    if InteractiveShell.initialized():
        # we are in a Shell environment, give %magic example
        config = "%config "
    else:
        # we are not in a shell, show generic config
        config = "c."
    print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr) 
Example 37
Project: Repobot   Author: Desgard   File: ultratb.py    MIT License 5 votes vote down vote up
def __call__(self, etype=None, evalue=None, etb=None):
        """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
        if etb is None:
            self.handler()
        else:
            self.handler((etype, evalue, etb))
        try:
            self.debugger()
        except KeyboardInterrupt:
            print("\nKeyboardInterrupt")


#---------------------------------------------------------------------------- 
Example 38
Project: Repobot   Author: Desgard   File: debugger.py    MIT License 5 votes vote down vote up
def BdbQuit_excepthook(et, ev, tb, excepthook=None):
    """Exception hook which handles `BdbQuit` exceptions.

    All other exceptions are processed using the `excepthook`
    parameter.
    """
    warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
                  DeprecationWarning, stacklevel=2)
    if et==bdb.BdbQuit:
        print('Exiting Debugger.')
    elif excepthook is not None:
        excepthook(et, ev, tb)
    else:
        # Backwards compatibility. Raise deprecation warning?
        BdbQuit_excepthook.excepthook_ori(et,ev,tb) 
Example 39
Project: Repobot   Author: Desgard   File: application.py    MIT License 5 votes vote down vote up
def init_crash_handler(self):
        """Create a crash handler, typically setting sys.excepthook to it."""
        self.crash_handler = self.crash_handler_class(self)
        sys.excepthook = self.excepthook
        def unset_crashhandler():
            sys.excepthook = sys.__excepthook__
        atexit.register(unset_crashhandler) 
Example 40
Project: Repobot   Author: Desgard   File: application.py    MIT License 5 votes vote down vote up
def excepthook(self, etype, evalue, tb):
        """this is sys.excepthook after init_crashhandler
        
        set self.verbose_crash=True to use our full crashhandler, instead of
        a regular traceback with a short message (crash_handler_lite)
        """
        
        if self.verbose_crash:
            return self.crash_handler(etype, evalue, tb)
        else:
            return crashhandler.crash_handler_lite(etype, evalue, tb) 
Example 41
Project: ns3   Author: KyleBenson   File: ipython_view.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,argv=None,user_ns=None,user_global_ns=None,
               cin=None, cout=None,cerr=None, input_func=None):
    if input_func:
      IPython.iplib.raw_input_original = input_func
    if cin:
      IPython.Shell.Term.cin = cin
    if cout:
      IPython.Shell.Term.cout = cout
    if cerr:
      IPython.Shell.Term.cerr = cerr

    if argv is None:
      argv=[]

    # This is to get rid of the blockage that occurs during 
    # IPython.Shell.InteractiveShell.user_setup()
    IPython.iplib.raw_input = lambda x: None

    self.term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr)
    os.environ['TERM'] = 'dumb'
    excepthook = sys.excepthook
    self.IP = IPython.Shell.make_IPython(argv,user_ns=user_ns,
                                         user_global_ns=user_global_ns,
                                         embedded=True,
                                         shell_class=IPython.Shell.InteractiveShell)
    self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd),
                                            header='IPython system call: ',
                                            verbose=self.IP.rc.system_verbose)
    sys.excepthook = excepthook
    self.iter_more = 0
    self.history_level = 0
    self.complete_sep =  re.compile('[\s\{\}\[\]\(\)]') 
Example 42
Project: iv   Author: kovidgoyal   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def closeEvent(self, ev):
        self.view.break_cycles()
        self.view.setParent(None)
        self.view = None
        self.setCentralWidget(None)
        sys.excepthook = sys.__excepthook__
        return super().closeEvent(ev) 
Example 43
Project: iv   Author: kovidgoyal   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def excepthook(self, exctype, value, traceback):
        if exctype == KeyboardInterrupt:
            return
        sys.__excepthook__(exctype, value, traceback)
        try:
            msg = str(value)
        except Exception:
            msg = repr(value)
        QMessageBox.critical(self, _('Unhandled error'), msg) 
Example 44
Project: jwalk   Author: jwplayer   File: __main__.py    Apache License 2.0 5 votes vote down vote up
def main():
    parser = create_parser()
    args = parser.parse_args()
    print("Args: ", args)

    if args.debug:
        sys.excepthook = debug_hook

    numeric_level = getattr(logging, args.log_level, None)
    logging.basicConfig(format=LOGFORMAT)
    logger.setLevel(numeric_level)

    return jwalk(**vars(args)) 
Example 45
Project: LaserTOF   Author: kyleuckert   File: backend_wx.py    MIT License 5 votes vote down vote up
def write(self, msg):
        print("Stderr: %s\n\r" % msg)

#if _DEBUG < 5:
    #sys.excepthook = debug_on_error
    #WxLogger =wx.LogStderr()
    #sys.stderr = fake_stderr

# the True dots per inch on the screen; should be display dependent
# see
# http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5
# for some info about screen dpi 
Example 46
Project: core   Author: getavalon   File: app.py    MIT License 5 votes vote down vote up
def show(root=None, debug=False, parent=None):
    """Display Scene Inventory GUI

    Arguments:
        debug (bool, optional): Run in debug-mode,
            defaults to False
        parent (QtCore.QObject, optional): When provided parent the interface
            to this QObject.

    """

    try:
        module.window.close()
        del module.window
    except (RuntimeError, AttributeError):
        pass

    if debug:
        import traceback
        sys.excepthook = lambda typ, val, tb: traceback.print_last()

    with tools_lib.application():
        window = Window(parent)
        window.show()
        window.setStyleSheet(style.load_stylesheet())
        window.refresh()

        module.window = window 
Example 47
Project: core   Author: getavalon   File: app.py    MIT License 5 votes vote down vote up
def show(debug=False, parent=None):
    """Display asset creator GUI

    Arguments:
        debug (bool, optional): Run loader in debug-mode,
            defaults to False
        parent (QtCore.QObject, optional): When provided parent the interface
            to this QObject.

    """

    if module.window:
        module.window.close()
        del(module.window)

    if debug:
        from avalon import mock
        for creator in mock.creators:
            api.register_plugin(api.Creator, creator)

        import traceback
        sys.excepthook = lambda typ, val, tb: traceback.print_last()

        io.install()

        any_project = next(
            project for project in io.projects()
            if project.get("active", True) is not False
        )

        api.Session["AVALON_PROJECT"] = any_project["name"]
        module.project = any_project["name"]

    with lib.application():
        window = Window(parent)
        window.refresh()
        window.show()
        window.setStyleSheet(style.load_stylesheet())

        module.window = window 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: cgitb.py    GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 49
Project: NiujiaoDebugger   Author: MrSrc   File: code.py    GNU General Public License v3.0 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

        The output is written by self.write(), below.

        """
        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
        if sys.excepthook is sys.__excepthook__:
            lines = traceback.format_exception_only(type, value)
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example 50
Project: NiujiaoDebugger   Author: MrSrc   File: weakref.py    GNU General Public License v3.0 5 votes vote down vote up
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()