我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用traceback.print_exception()。
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])
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)
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())
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
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')
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().
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)
def run(self, records, total=None, fast_run=True, write=True): # this shouldn't ever actually get used now raise ValueError() records = self.filter(records) for record in tqdm(records, mininterval=2, total=total): gene = self.GENE_CLASS(record, self.organism_info, self.login) try: gene.create_item(fast_run=fast_run, write=write) except Exception as e: exc_info = sys.exc_info() traceback.print_exception(*exc_info) msg = wdi_helpers.format_msg(gene.external_ids['Entrez Gene ID'], PROPS['Entrez Gene ID'], None, str(e), msg_type=type(e)) wdi_core.WDItemEngine.log("ERROR", msg) gene.status = msg if gene.status is not True: self.failed.append(gene.entrez)
def run(self, records, total=None, fast_run=True, write=True): records = self.filter(records) for record in tqdm(records, mininterval=2, total=total): # print(record['entrezgene']) gene = self.GENE_CLASS(record, self.organism_info, self.chr_num_wdid, self.login) try: gene.create_item(fast_run=fast_run, write=write) except Exception as e: exc_info = sys.exc_info() traceback.print_exception(*exc_info) msg = wdi_helpers.format_msg(gene.external_ids['Entrez Gene ID'], PROPS['Entrez Gene ID'], None, str(e), msg_type=type(e)) wdi_core.WDItemEngine.log("ERROR", msg) gene.status = msg if gene.status is not True: self.failed.append(gene.entrez)
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)
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)
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
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
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
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)
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
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")
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')
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)
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
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)
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)
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'), ))
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)
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")
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.")
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
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)
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
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])
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 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
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)
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()
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 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)
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()
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()
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,
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