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
python类print_exception()的实例源码
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 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 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 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 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
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 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,