Python traceback.print_exception() Examples

The following are code examples for showing how to use traceback.print_exception(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: scheduled-bots   Author: SuLab   File: ProteinBot.py    (license) View Source Project 7 votes vote down vote up
def make_gene_encodes(self, write=True):
        """
        Add an "encodes" statement to the gene item
        :return:
        """
        uniprot_ref = make_ref_source(self.record['uniprot']['@source'], PROPS['UniProt ID'],
                                      self.external_ids['UniProt ID'],
                                      login=self.login)

        try:
            statements = [wdi_core.WDItemID(self.protein_wdid, PROPS['encodes'], references=[uniprot_ref])]
            wd_item_gene = wdi_core.WDItemEngine(wd_item_id=self.gene_wdid, domain='genes', data=statements,
                                                 append_value=[PROPS['encodes']], fast_run=fast_run,
                                                 fast_run_base_filter={PROPS['Entrez Gene ID']: '',
                                                                       PROPS['found in taxon']: self.organism_info[
                                                                           'wdid']},
                                                 global_ref_mode="CUSTOM", ref_handler=update_retrieved_if_new)
            wdi_helpers.try_write(wd_item_gene, self.external_ids['UniProt ID'], PROPS['UniProt ID'], self.login,
                                  write=write)
        except Exception as e:
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            msg = wdi_helpers.format_msg(self.external_ids['UniProt ID'], PROPS['UniProt ID'], None,
                                         str(e), msg_type=type(e))
            wdi_core.WDItemEngine.log("ERROR", msg) 
Example 2
Project: kiota   Author: Morteo   File: Util.py    (MIT License) View Source Project 6 votes vote down vote up
def log(o, t, e=None):
  if e is None:
    print("{}: {}".format(type(o).__name__, t))
  else:
    print("{}: {} Exception:{!r}".format(type(o).__name__, t, e))
    import sys
    if hasattr(sys, 'print_exception'):
      sys.print_exception(e)
    else:
      import traceback
      traceback.print_exception(type(e), e, sys.exc_info()[2]) 
Example 3
Project: core-framework   Author: RedhawkSDR   File: notify.py    (license) View Source Project 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        if self.nc_match:
            # Prevent malformed match functions from derailing the entire
            # notification process
            try:
                match = self.nc_match(*args, **kwargs)
            except:
                print >>sys.stderr, 'Exception in match function for notification %s:' % (repr(self.nc_func),)
                traceback.print_exception(*sys.exc_info())

                # Treat an exception in the function as a negative response
                match = False

            if not match:
                return None
        return self.nc_func(*args, **kwargs) 
Example 4
Project: core-framework   Author: RedhawkSDR   File: notify.py    (license) View Source Project 6 votes vote down vote up
def notify(self, *args, **kwargs):
        """
        Call all listener callbacks. The wrapped function is not executed.
        """
        for listener in self.nm_listeners:
            # Ensure that all callbacks get called, and no exceptions escape to
            # the caller.
            try:
                listener(*args, **kwargs)
            except:
                # If the target is a notify_callback--which should always be
                # the case as long as the proper API is used--show the actual
                # function
                target = getattr(listener, 'nc_func', listener)
                print >>sys.stderr, 'Exception in notification %s:' % (repr(target),)
                traceback.print_exception(*sys.exc_info()) 
Example 5
Project: kinect-2-libras   Author: inessadl   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions:
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 6
Project: speccer   Author: bensimner   File: spec.py    (MIT License) View Source Project 6 votes vote down vote up
def _print_failure(prop, depth, failure, outfile=sys.stdout):
    outfile.write('=' * 80)
    outfile.write('\n')

    outfile.write('Failure\n')
    _print_prop_summary(prop, failure, outfile=outfile)
    outfile.write('{} ->\n'.format(failure.prop.name))
    if isinstance(failure, clauses.Counter):
        outfile.write(' counterexample:\n')
        _print_arg(failure.reason, outfile=outfile)
        _print_reason(failure, outfile=outfile)
    elif isinstance(failure, clauses.UnrelatedException):
        outfile.write(' exception:\n')
        outfile.write('\n')
        e = failure.reason
        traceback.print_exception(type(e), e, e.__traceback__, file=outfile)
    elif isinstance(failure, clauses.NoWitness):
        outfile.write(' no witness.\n')
    outfile.write('\n')
    _print_parents(failure, outfile=outfile)

    outfile.write('\nFAIL\n') 
Example 7
Project: mongodb-monitoring   Author: jruaux   File: monitoring.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _handle_exception():
    """Print exceptions raised by subscribers to stderr."""
    # Heavily influenced by logging.Handler.handleError.

    # See note here:
    # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
    if sys.stderr:
        einfo = sys.exc_info()
        try:
            traceback.print_exception(einfo[0], einfo[1], einfo[2],
                                      None, sys.stderr)
        except IOError:
            pass
        finally:
            del einfo

# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower(). 
Example 8
Project: Harmonbot   Author: Harmon758   File: twitter.py    (license) View Source Project 6 votes vote down vote up
def start_twitter_feeds(self):
		await self.bot.wait_until_ready()
		feeds = {}
		for channel_id, channel_info in self.feeds_info["channels"].items():
			for handle in channel_info["handles"]:
				try:
					feeds[channel_id] = feeds.get(channel_id, []) + [clients.twitter_api.get_user(handle).id_str]
				except tweepy.error.TweepError as e:
					if e.api_code == 50:
					# User not found
						continue
					else:
						print("Exception in Twitter Task", file = sys.stderr)
						traceback.print_exception(type(e), e, e.__traceback__, file = sys.stderr)
						logging.errors_logger.error("Uncaught Twitter Task exception\n", exc_info = (type(e), e, e.__traceback__))
						return
		await self.stream_listener.start_feeds(feeds = feeds) 
Example 9
Project: scheduled-bots   Author: SuLab   File: obographs.py    (license) View Source Project 6 votes vote down vote up
def create_depend(self, login=None, write=True):
        if self.deprecated:
            return None
        if not self.wd_item_id:
            print("must create item first: {}".format(node.id_purl))
            return None
        try:
            s = self.create_main_statements()
            wd_item = wdi_core.WDItemEngine(wd_item_id=self.wd_item_id, data=s, domain=self.domain,
                                            append_value=[PROPS['subclass of'], PROPS['instance of']],
                                            fast_run=self.fast_run,
                                            fast_run_base_filter={self.primary_ext_prop_qid: ''})
            wdi_helpers.try_write(wd_item, record_id=self.id_colon, record_prop=self.primary_ext_prop_qid, login=login,
                                  write=write)
            return wd_item
        except Exception as e:
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            msg = wdi_helpers.format_msg(self.id_colon, self.primary_ext_prop_qid, None, str(e), msg_type=type(e))
            wdi_core.WDItemEngine.log("ERROR", msg) 
Example 10
Project: xmpp-cloud-auth   Author: jsxc   File: roster_thread.py    (license) View Source Project 6 votes vote down vote up
def roster_background_thread(self, sr):
        '''Entry for background roster update thread'''
        try:
            logging.debug('roster_thread for ' + str(sr))
            # Allow test hooks with static ejabberd_controller
            if hasattr(self.ctx, 'ejabberd_controller') and self.ctx.ejabberd_controller is not None:
                e = self.ctx.ejabberd_controller
            else:
                e = ejabberdctl(self.ctx)
            groups, commands = self.roster_update_users(e, sr)
            self.roster_update_groups(e, groups)
            # For some reason, the vcard changes are not pushed to the clients. Rinse and repeat.
# Maybe not necessary with synchronous thread?
#            for cmd in commands:
#                e.execute(cmd)
            self.ctx.shared_roster_db.sync()
        except AttributeError:
            pass # For tests
        except Exception, err:
            (etype, value, tb) = sys.exc_info()
            traceback.print_exception(etype, value, tb)
            logging.warn('roster_groups thread: %s:\n%s'
                         % (str(err), ''.join(traceback.format_tb(tb))))
            return False 
Example 11
Project: hostapd-mana   Author: adde88   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 12
Project: lemongraph   Author: NationalSecurityAgency   File: server.py    (license) View Source Project 6 votes vote down vote up
def input(self):
        try:
            encoded = ''.join(self.body)
            if len(encoded) == 0:
                return None
            unpacker = self.content_types[self.content_type]
            data = unpacker(encoded)
        except KeyError:
            raise HTTPError(409, 'Bad/missing mime type (%s) - use one of: %s' % (self.content_type, ', '.join(self.content_types.keys())))
        except ValueError:
            raise HTTPError(400, 'Decode failed for mime type: %s' % self.content_type)
        except HTTPError:
            raise
        except Exception as e:
            info = sys.exc_info()
            log.error('Unhandled exception: %s', traceback.print_exception(*info))
            raise HTTPError(409, 'Bad data - %s decode failed' % self.content_type)
        return data

    # called for each request 
Example 13
Project: weibo   Author: windskyer   File: log.py    (license) View Source Project 6 votes vote down vote up
def formatException(self, exc_info, record=None):
        """Format exception output with CONF.logging_exception_prefix."""
        if not record:
            return logging.Formatter.formatException(self, exc_info)

        stringbuffer = cStringIO.StringIO()
        traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
                                  None, stringbuffer)
        lines = stringbuffer.getvalue().split('\n')
        stringbuffer.close()

        if CONF.logging_exception_prefix.find('%(asctime)') != -1:
            record.asctime = self.formatTime(record, self.datefmt)

        formatted_lines = []
        for line in lines:
            pl = CONF.logging_exception_prefix % record.__dict__
            fl = '%s%s' % (pl, line)
            formatted_lines.append(fl)
        return '\n'.join(formatted_lines) 
Example 14
Project: pg2xls   Author: CarlosCorreiaM16e   File: pg2xls.py    (license) View Source Project 6 votes vote down vote up
def get_password( username ):
    try:
        f = open( '%s/.pgpass' % os.environ[ 'HOME' ], "r" )
        lines = f.readlines()
        f.close()
        for l in lines:
            flds = l.split( ':' )
            if username == flds[ 3 ]:
                password = flds[ 4 ].strip()
                break

    except:
        t, v, tb = sys.exc_info()
        traceback.print_exception( t, v, tb )
        password = raw_input( 'Password: ' )
    return password


#------------------------------------------------------------------
# main 
Example 15
Project: style50   Author: cs50   File: __main__.py    (license) View Source Project 6 votes vote down vote up
def excepthook(etype, value, tb):
    if etype is Error:
        termcolor.cprint(value.msg, "red", file=sys.stderr)
    else:
        termcolor.cprint("Sorry, something's wrong! "
                         "Let [email protected] know!",
                         "red", file=sys.stderr)

    # Main might not have initialized args yet.
    try:
        verbose = main.args.verbose
    except AttributeError:
        verbose = True

    if verbose:
        traceback.print_exception(etype, value, tb)


# Set global exception handler. 
Example 16
Project: HARK   Author: econ-ark   File: ModelTesting.py    (license) View Source Project 6 votes vote down vote up
def traceback(self):
        '''
        function that prints a traceback for an errror

        Inputs
        ----------   
        none
        
        Returns
        ----------   
        None

        '''
        try:
            traceback.print_exception(*self._tracebackText)
        except TypeError:
            print("The test was run successfully - no error generated") 
Example 17
Project: Intranet-Penetration   Author: yuxiaokui   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 18
Project: Intranet-Penetration   Author: yuxiaokui   File: greenlet.py    (license) View Source Project 6 votes vote down vote up
def _report_error(self, exc_info):
        exception = exc_info[1]
        if isinstance(exception, GreenletExit):
            self._report_result(exception)
            return
        try:
            traceback.print_exception(*exc_info)
        except:
            pass
        self._exception = exception

        if self._links and self._notifier is None:
            self._notifier = core.active_event(self._notify_links)

        info = str(self) + ' failed with '
        try:
            info += self._exception.__class__.__name__
        except Exception:
            info += str(self._exception) or repr(self._exception)
        sys.stderr.write(info + '\n\n') 
Example 19
Project: q2cli   Author: qiime2   File: util.py    (license) View Source Project 6 votes vote down vote up
def exit_with_error(e, header='An error has been encountered:', file=None,
                    suppress_footer=False):
    import sys
    import traceback
    import textwrap
    import click

    if file is None:
        file = sys.stderr
        footer = 'See above for debug info.'
    else:
        footer = 'Debug info has been saved to %s' % file.name

    error = textwrap.indent(str(e), '  ')

    segments = [header, error]
    if not suppress_footer:
        segments.append(footer)

    traceback.print_exception(type(e), e, e.__traceback__, file=file)
    file.write('\n')

    click.secho('\n\n'.join(segments), fg='red', bold=True, err=True)

    click.get_current_context().exit(1) 
Example 20
Project: node-agent   Author: Tendrl   File: handler.py    (license) View Source Project 6 votes vote down vote up
def bind_unix_listener(self):
        # http://0pointer.de/blog/projects/systemd.html (search "file
        # descriptor 3")
        try:
            socket_fd = 3
            self.sock = socket.fromfd(socket_fd, socket.AF_UNIX,
                                      socket.SOCK_STREAM)
            self.sock.listen(50)
            return self.sock
        except (TypeError, BlockingIOError, socket.error, ValueError):
            pass
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            if os.path.exists(MESSAGE_SOCK_PATH):
                os.remove(MESSAGE_SOCK_PATH)
            self.sock.bind(MESSAGE_SOCK_PATH)
            self.sock.listen(50)
            return self.sock
        except Exception as ex:
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_tb,
                                      file=sys.stderr)
            raise ex 
Example 21
Project: MKFQ   Author: maojingios   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 22
Project: MKFQ   Author: maojingios   File: greenlet.py    (license) View Source Project 6 votes vote down vote up
def _report_error(self, exc_info):
        exception = exc_info[1]
        if isinstance(exception, GreenletExit):
            self._report_result(exception)
            return
        try:
            traceback.print_exception(*exc_info)
        except:
            pass
        self._exception = exception

        if self._links and self._notifier is None:
            self._notifier = core.active_event(self._notify_links)

        info = str(self) + ' failed with '
        try:
            info += self._exception.__class__.__name__
        except Exception:
            info += str(self._exception) or repr(self._exception)
        sys.stderr.write(info + '\n\n') 
Example 23
Project: dd-trace-py   Author: DataDog   File: span.py    (license) View Source Project 6 votes vote down vote up
def set_exc_info(self, exc_type, exc_val, exc_tb):
        """ Tag the span with an error tuple as from `sys.exc_info()`. """
        if not (exc_type and exc_val and exc_tb):
            return # nothing to do

        self.error = 1

        # get the traceback
        buff = StringIO()
        traceback.print_exception(exc_type, exc_val, exc_tb, file=buff, limit=20)
        tb = buff.getvalue()

        # readable version of type (e.g. exceptions.ZeroDivisionError)
        exc_type_str = "%s.%s" % (exc_type.__module__, exc_type.__name__)

        self.set_tag(errors.ERROR_MSG, exc_val)
        self.set_tag(errors.ERROR_TYPE, exc_type_str)
        self.set_tag(errors.ERROR_STACK, tb) 
Example 24
Project: oa_qian   Author: sunqb   File: hub.py    (license) View Source Project 6 votes vote down vote up
def handle_error(self, context, type, value, tb):
        """
        Called by the event loop when an error occurs. The arguments
        type, value, and tb are the standard tuple returned by :func:`sys.exc_info`.

        Applications can set a property on the hub with this same signature
        to override the error handling provided by this class.

        Errors that are :attr:`system errors <SYSTEM_ERROR>` are passed
        to :meth:`handle_system_error`.

        :param context: If this is ``None``, indicates a system error that
            should generally result in exiting the loop and being thrown to the
            parent greenlet.
        """
        if isinstance(value, str):
            # Cython can raise errors where the value is a plain string
            # e.g., AttributeError, "_semaphore.Semaphore has no attr", <traceback>
            value = type(value)
        if not issubclass(type, self.NOT_ERROR):
            self.print_exception(context, type, value, tb)
        if context is None or issubclass(type, self.SYSTEM_ERROR):
            self.handle_system_error(type, value) 
Example 25
Project: oa_qian   Author: sunqb   File: hub.py    (license) View Source Project 6 votes vote down vote up
def print_exception(self, context, type, value, tb):
        # Python 3 does not gracefully handle None value or tb in
        # traceback.print_exception() as previous versions did.
        if value is None:
            sys.stderr.write('%s\n' % type.__name__)
        else:
            traceback.print_exception(type, value, tb)
        del tb
        if context is not None:
            if not isinstance(context, str):
                try:
                    context = self.format_context(context)
                except:
                    traceback.print_exc()
                    context = repr(context)
            sys.stderr.write('%s failed with %s\n\n' % (context, getattr(type, '__name__', 'exception'), )) 
Example 26
Project: RealtimePythonChat   Author: quangtqag   File: hub.py    (license) View Source Project 6 votes vote down vote up
def handle_error(self, context, type, value, tb):
        """
        Called by the event loop when an error occurs. The arguments
        type, value, and tb are the standard tuple returned by :func:`sys.exc_info`.

        Applications can set a property on the hub with this same signature
        to override the error handling provided by this class.

        Errors that are :attr:`system errors <SYSTEM_ERROR>` are passed
        to :meth:`handle_system_error`.

        :param context: If this is ``None``, indicates a system error that
            should generally result in exiting the loop and being thrown to the
            parent greenlet.
        """
        if isinstance(value, str):
            # Cython can raise errors where the value is a plain string
            # e.g., AttributeError, "_semaphore.Semaphore has no attr", <traceback>
            value = type(value)
        if not issubclass(type, self.NOT_ERROR):
            self.print_exception(context, type, value, tb)
        if context is None or issubclass(type, self.SYSTEM_ERROR):
            self.handle_system_error(type, value) 
Example 27
Project: spc   Author: whbrewer   File: app_routes.py    (license) View Source Project 6 votes vote down vote up
def show_app(app):
    # very similar to start_new_job() consider consolidating
    user = root.authorized()
    root.set_active(app)
    # parameters for return template
    if app not in root.myapps:
        return template('error', err="app %s is not installed" % (app))

    try:
        params = {}
        params.update(root.myapps[app].params)
        params['cid'] = ''
        params['app'] = app
        params['user'] = user
        params['apps'] = root.myapps
        return template(os.path.join('apps', app),  params)
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print traceback.print_exception(exc_type, exc_value, exc_traceback)
        redirect('/app/'+app) 
Example 28
Project: spc   Author: whbrewer   File: app_routes.py    (license) View Source Project 6 votes vote down vote up
def delete_app(appid):
    user = root.authorized()
    if user != 'admin':
        return template('error', err="must be admin to edit app")
    appname = request.forms.app
    del_app_dir = request.forms.del_app_dir

    try:
        if user == 'admin':
            # delete entry in DB
            if del_app_dir == "on":
                del_files = True
            else:
                del_files = False
            root.myapps[appname].delete(appid, del_files)
        else:
            return template("error", err="must be admin")
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print traceback.print_exception(exc_type, exc_value, exc_traceback)
        return template("error", err="failed to delete app... did the app load properly?")

    redirect("/apps") 
Example 29
Project: spc   Author: whbrewer   File: app_routes.py    (license) View Source Project 6 votes vote down vote up
def view_app(app):
    user = root.authorized()
    if app: root.set_active(app)
    else: redirect('/myapps')

    if user != 'admin':
        return template('error', err="must be admin to edit app")
    cid = request.query.cid
    result = db(apps.name==app).select().first()
    params = {}
    params['app'] = app
    params['user'] = user
    params['cid'] = cid
    #if request.query.edit:
    #    return template('appedit', params, rows=result)
    #else:
    try:
        return template('app', params, rows=result)
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print traceback.print_exception(exc_type, exc_value, exc_traceback)
        return template('error', err="there was a problem showing the app template. Check traceback.") 
Example 30
Project: spc   Author: whbrewer   File: main.py    (license) View Source Project 6 votes vote down vote up
def load_apps():
    """load apps into myapps global dictionary"""
    global myapps, default_app
    # Connect to DB
    result = db().select(apps.ALL)
    myapps = {}
    for row in result:
        name = row['name']
        appid = row['id']
        preprocess = row['preprocess']
        postprocess = row['postprocess']
        input_format = row['input_format']
        try:
            print 'loading: %s (id: %s)' % (name, appid)
            myapps[name] = app_instance(input_format, name, preprocess, postprocess)
            myapps[name].appid = appid
            myapps[name].input_format = input_format
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print traceback.print_exception(exc_type, exc_value, exc_traceback)
            print 'ERROR: LOADING: %s (ID: %s) FAILED TO LOAD' % (name, appid)
    default_app = name # simple soln - use last app read from DB
    return True 
Example 31
Project: spc   Author: whbrewer   File: test.py    (license) View Source Project 6 votes vote down vote up
def load_apps():
    """load apps into myapps global dictionary"""
    global myapps, default_app
    # Connect to DB
    result = db().select(apps.ALL)
    myapps = {}
    for row in result:
        name = row['name']
        appid = row['id']
        preprocess = row['preprocess']
        postprocess = row['postprocess']
        input_format = row['input_format']
        try:
            print 'loading: %s (id: %s)' % (name, appid)
            myapps[name] = app_instance(input_format, name, preprocess, postprocess)
            myapps[name].appid = appid
            myapps[name].input_format = input_format
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print traceback.print_exception(exc_type, exc_value, exc_traceback)
            print 'ERROR: LOADING: %s (ID: %s) FAILED TO LOAD' % (name, appid)
    default_app = name # simple soln - use last app read from DB
    return True 
Example 32
Project: endrebot0   Author: endreman0   File: fragment.py    (license) View Source Project 6 votes vote down vote up
def invoke(self, ctx):
		locals_ = locals().copy()
		try:
			load_function(self.code, dict(globals(), **ctx.bot.commands), locals_)
		except SyntaxError as err:
			traceback.print_exception(type(err), err, err.__traceback__)
			return 'SyntaxError: %s' % err
		
		try:
			ret = await locals_['evaluation'](ctx)
			if asyncio.iscoroutine(ret):
				ret = await ret
			elif ret in ctx.bot.commands.values():
				ret = await ret() if asyncio.iscoroutinefunction(ret) else ret()
		except Exception as err:
			traceback.print_exception(type(err), err, err.__traceback__)
			return '%s: %s' % (type(err).__name__, err)
		else:
			return str(ret) 
Example 33
Project: jvcprojectortools   Author: arvehj   File: menu.py    (license) View Source Project 6 votes vote down vote up
def main():
    """JVC Projector tools main menu"""
    while True:
        try:
            Menu()
            break
        except Exception as err:
            if isinstance(err, ExceptionInThread):
                err, exc = err.args
            else:
                exc = sys.exc_info()
            print(err)
            try:
                if strtobool(input('error occured print stack trace? ')):
                    traceback.print_exception(*exc)
            except:
                pass
            try:
                if not strtobool(input('restart? ')):
                    break
            except:
                break 
Example 34
Project: leetcode   Author: thomasyimgit   File: formatters.py    (license) View Source Project 6 votes vote down vote up
def catch_format_error(method, self, *args, **kwargs):
    """show traceback on failed format call"""
    try:
        r = method(self, *args, **kwargs)
    except NotImplementedError:
        # don't warn on NotImplementedErrors
        return None
    except Exception:
        exc_info = sys.exc_info()
        ip = get_ipython()
        if ip is not None:
            ip.showtraceback(exc_info)
        else:
            traceback.print_exception(*exc_info)
        return None
    return self._check_return(r, args[0]) 
Example 35
Project: MDT   Author: cbclab   File: utils.py    (license) View Source Project 6 votes vote down vote up
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 
Example 36
Project: zippy   Author: securesystemslab   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def formatException(self, ei):
        """
        Format and return the specified exception information as a string.

        This default implementation just uses
        traceback.print_exception()
        """
        sio = io.StringIO()
        tb = ei[2]
        # See issues #9427, #1553375. Commented out for now.
        #if getattr(self, 'fullstack', False):
        #    traceback.print_stack(tb.tb_frame.f_back, file=sio)
        traceback.print_exception(ei[0], ei[1], tb, None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1:] == "\n":
            s = s[:-1]
        return s 
Example 37
Project: zippy   Author: securesystemslab   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 38
Project: zippy   Author: securesystemslab   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline.  If
        exception information is present, it is formatted using
        traceback.print_exception and appended to the stream.  If the stream
        has an 'encoding' attribute, it is used to determine how to do the
        output to the stream.
        """
        try:
            msg = self.format(record)
            stream = self.stream
            stream.write(msg)
            stream.write(self.terminator)
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record) 
Example 39
Project: zippy   Author: securesystemslab   File: run.py    (license) View Source Project 6 votes vote down vote up
def runcode(self, code):
        global interruptable
        try:
            self.usr_exc_info = None
            interruptable = True
            try:
                exec(code, self.locals)
            finally:
                interruptable = False
        except:
            self.usr_exc_info = sys.exc_info()
            if quitting:
                exit()
            # even print a user code SystemExit exception, continue
            print_exception()
            jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
            if jit:
                self.rpchandler.interp.open_remote_stack_viewer()
        else:
            flush_stdout() 
Example 40
Project: incubator-ariatosca   Author: apache   File: aria.py    (license) View Source Project 6 votes vote down vote up
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 
Example 41
Project: incubator-ariatosca   Author: apache   File: exceptions.py    (license) View Source Project 6 votes vote down vote up
def print_exception(e, full=True, cause=False, traceback=None):
    """
    Prints the exception with nice colors and such.
    """
    def format_heading(e):
        return '{0}{1}: {2}'.format(
            Colored.red('Caused by ') if cause else '',
            Colored.red(e.__class__.__name__, bold=True),
            Colored.red(e))

    puts(format_heading(e))
    if full:
        if cause:
            if traceback:
                print_traceback(traceback, True)
        else:
            print_traceback()
    if hasattr(e, 'cause') and e.cause:
        traceback = e.cause_traceback if hasattr(e, 'cause_traceback') else None
        print_exception(e.cause, full=full, cause=True, traceback=traceback) 
Example 42
Project: yt   Author: yt-project   File: funcs.py    (license) View Source Project 6 votes vote down vote up
def paste_traceback(exc_type, exc, tb):
    """
    This is a traceback handler that knows how to paste to the pastebin.
    Should only be used in sys.excepthook.
    """
    sys.__excepthook__(exc_type, exc, tb)
    from yt.extern.six.moves import StringIO, xmlrpc_client
    p = xmlrpc_client.ServerProxy(
            "http://paste.yt-project.org/xmlrpc/",
            allow_none=True)
    s = StringIO()
    traceback.print_exception(exc_type, exc, tb, file=s)
    s = s.getvalue()
    ret = p.pastes.newPaste('pytb', s, None, '', '', True)
    print()
    print("Traceback pasted to http://paste.yt-project.org/show/%s" % (ret))
    print() 
Example 43
Project: yt   Author: yt-project   File: rpdb.py    (license) View Source Project 6 votes vote down vote up
def rpdb_excepthook(exc_type, exc, tb):
    traceback.print_exception(exc_type, exc, tb)
    task = ytcfg.getint("yt", "__global_parallel_rank")
    size = ytcfg.getint("yt", "__global_parallel_size")
    print("Starting RPDB server on task %s ; connect with 'yt rpdb -t %s'" \
            % (task,task))
    handler = pdb_handler(tb)
    server = PdbXMLRPCServer(("localhost", 8010+task))
    server.register_introspection_functions()
    server.register_instance(handler)
    server.register_function(server.shutdown)
    server.serve_forever()
    server.server_close()
    if size > 1:
        from mpi4py import MPI
        # This COMM_WORLD is okay.  We want to barrierize here, while waiting
        # for shutdown from the rest of the parallel group.  If you are running
        # with --rpdb it is assumed you know what you are doing and you won't
        # let this get out of hand.
        MPI.COMM_WORLD.Barrier() 
Example 44
Project: oil   Author: oilshell   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 45
Project: oil   Author: oilshell   File: run.py    (license) View Source Project 6 votes vote down vote up
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line, 
Example 46
Project: python2-tracer   Author: extremecoders-re   File: pysvr.py    (license) View Source Project 6 votes vote down vote up
def run_command(code, stdin, stdout, globals):
    save = sys.stdin, sys.stdout, sys.stderr
    try:
        sys.stdout = sys.stderr = stdout
        sys.stdin = stdin
        try:
            exec code in globals
        except SystemExit, how:
            raise SystemExit, how, sys.exc_info()[2]
        except:
            type, value, tb = sys.exc_info()
            if tb: tb = tb.tb_next
            traceback.print_exception(type, value, tb)
            del tb
    finally:
        sys.stdin, sys.stdout, sys.stderr = save 
Example 47
Project: python2-tracer   Author: extremecoders-re   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 48
Project: python2-tracer   Author: extremecoders-re   File: run.py    (license) View Source Project 6 votes vote down vote up
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line, 
Example 49
Project: python2-tracer   Author: extremecoders-re   File: run.py    (license) View Source Project 6 votes vote down vote up
def runcode(self, code):
        global interruptable
        try:
            self.usr_exc_info = None
            interruptable = True
            try:
                exec code in self.locals
            finally:
                interruptable = False
        except SystemExit:
            # Scripts that raise SystemExit should just
            # return to the interactive prompt
            pass
        except:
            self.usr_exc_info = sys.exc_info()
            if quitting:
                exit()
            print_exception()
            jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
            if jit:
                self.rpchandler.interp.open_remote_stack_viewer()
        else:
            flush_stdout() 
Example 50
Project: PINCE   Author: korcankaraokcu   File: PINCE.py    (license) View Source Project 6 votes vote down vote up
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()