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])
python类print_exception()的实例源码
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 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 _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 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 _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 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 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 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.")