本文整理汇总了Python中traceback.format_exception函数的典型用法代码示例。如果您正苦于以下问题:Python format_exception函数的具体用法?Python format_exception怎么用?Python format_exception使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_exception函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply
def apply(catalog, goal):
"""
Apply the goal configuration to live catalog
"""
print 'applying...'
counter = 0
ready = False
while ready == False:
try:
catalog.applyCatalogConfig(goal)
ready = True
except HTTPError as err:
print err
print err.errno
if err.errno == CONFLICT:
et, ev, tb = sys.exc_info()
print 'Conflict Exception "%s"' % str(ev)
counter = counter + 1
if counter >= 5:
print '%s' % str(traceback.format_exception(et, ev, tb))
ready = True
else:
print 'Retrying...'
except:
et, ev, tb = sys.exc_info()
print str(et)
print 'Exception "%s"' % str(ev)
print '%s' % str(traceback.format_exception(et, ev, tb))
ready = True
示例2: process_feed_wrapper
def process_feed_wrapper(self, feed):
""" wrapper for ProcessFeed
"""
start_time = datetime.datetime.now()
try:
pfeed = ProcessFeed(feed, self.options)
ret_feed, ret_entries = pfeed.process()
del pfeed
except:
(etype, eobj, etb) = sys.exc_info()
print '[%d] ! -------------------------' % (feed.id,)
print traceback.format_exception(etype, eobj, etb)
traceback.print_exception(etype, eobj, etb)
print '[%d] ! -------------------------' % (feed.id,)
ret_feed = FEED_ERREXC
ret_entries = {}
delta = datetime.datetime.now() - start_time
if delta.seconds > SLOWFEED_WARNING:
comment = u' (SLOW FEED!)'
else:
comment = u''
prints(u'[%d] Processed %s in %s [%s] [%s]%s' % (
feed.id, feed.feed_url, unicode(delta),
self.feed_trans[ret_feed],
u' '.join(u'%s=%d' % (self.entry_trans[key],
ret_entries[key]) for key in self.entry_keys),
comment))
self.feed_stats[ret_feed] += 1
for key, val in ret_entries.items():
self.entry_stats[key] += val
return ret_feed, ret_entries
示例3: _exc_info_to_string
def _exc_info_to_string(self, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and self._is_relevant_tb_level(tb):
tb = tb.tb_next
if exctype is test.failureException:
# Skip assert*() traceback levels
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
if self.buffer:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
msgLines.append(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
msgLines.append(STDERR_LINE % error)
return ''.join(msgLines)
示例4: __printFail
def __printFail(self, test, err):
elapsed = time.time() - self.startTime
t, val, trace = err
if args.testpilot_json:
print(
json.dumps(
{
"op": "test_done",
"status": "failed",
"test": test.id(),
"details": "".join(traceback.format_exception(t, val, trace)),
"start_time": self.startTime,
"end_time": time.time(),
}
)
)
else:
print(
"\033[31mFAIL\033[0m %s (%.3fs)%s\n%s"
% (
test.id(),
elapsed,
self._attempts(),
"".join(traceback.format_exception(t, val, trace)),
)
)
示例5: build_error_response
def build_error_response(e):
if hasattr(e,'get_stacks'):
#Process potentially multiple stacks.
full_error = ''
for i in range(len(e.get_stacks())):
full_error += e.get_stacks()[i][0] + "\n"
if i == 0:
full_error += string.join(traceback.format_exception(*sys.exc_info()), '')
else:
for ln in e.get_stacks()[i][1]:
full_error += str(ln) + "\n"
exec_name = e.__class__.__name__
else:
exc_type, exc_obj, exc_tb = sys.exc_info()
exec_name = exc_type.__name__
full_error = traceback.format_exception(*sys.exc_info())
if service_gateway_instance.log_errors:
log.error(full_error)
result = {
GATEWAY_ERROR_EXCEPTION : exec_name,
GATEWAY_ERROR_MESSAGE : str(e.message),
GATEWAY_ERROR_TRACE : full_error
}
if request.args.has_key(RETURN_FORMAT_PARAM):
return_format = convert_unicode(request.args[RETURN_FORMAT_PARAM])
if return_format == RETURN_FORMAT_RAW_JSON:
return service_gateway_app.response_class(result, mimetype='application/json')
return json_response({'data': {GATEWAY_ERROR: result }} )
示例6: run
def run(self):
"""
Thread main part
"""
## testlink = threading.Timer(3.0,gprs_source.writeTest)
## testlink.start()
while not self.exitEvent.isSet():
asyncore.poll(0.5) # socket IO
try: ## lower device IO
for i in self.device: #如果连接网关的本地客户端不为空,那么循环读取数据,发送命令
try:
pkts = i.readPackets()#返回的就是python字典形式的包
except:
pass
else:
if pkts:
self.clientMessageSource.setMessage(pkts)
command = self.clientMessageSource.getLowerPacket()
print "+++++++"+str(command)
i.writePackets(command)
except:
type, value, tb = sys.exc_info()
print traceback.format_exception(type, value, tb)
pass
示例7: unix_mainloop
def unix_mainloop(repodir, port, logfilename):
try:
port = int(port)
except ValueError:
port = None
if not os.path.isdir(repodir):
sys.stderr.write("Specified directory, %s, is not a directory!\n" % repodir)
usage()
elif port is None:
sys.stderr.write("Bad port number, %s, specified.\n", portnum)
usage()
try:
repo = start_angel(repodir, port, logfilename)
except:
sys.stderr.write("%s: exception initializing angel:\n%s" % (
time.ctime(), ''.join(traceback.format_exception(*sys.exc_info()))))
sys.exit(1)
# Finally, start up the server loop! This loop will not exit until
# all clients and servers are closed. You may cleanly shut the system
# down by sending SIGINT (a.k.a. KeyboardInterrupt).
from uplib.plibUtil import note
while True:
try:
asyncore.loop()
except (KeyboardInterrupt, SystemExit), x:
note(4, "Exited from main loop due to exception:\n%s", ''.join(traceback.format_exception(*sys.exc_info())))
raise
except:
示例8: create_authnrequest
def create_authnrequest(self, environ, server_env, start_response, session, acr_value):
try:
client = session.getClient()
session.setAcrValue(client.authorization_endpoint, acr_value)
request_args = {
"response_type": self.flow_type,
"scope": self.extra["scope"],
"state": client.state,
}
if acr_value is not None:
request_args["acr_values"] = acr_value
if self.flow_type == "token":
request_args["nonce"] = rndstr(16)
session.setNonce(request_args["nonce"])
else:
use_nonce = getattr(self, "use_nonce", None)
if use_nonce:
request_args["nonce"] = rndstr(16)
session.setNonce(request_args["nonce"])
logger.info("client args: %s" % client.__dict__.items(),)
logger.info("request_args: %s" % (request_args,))
# User info claims
except Exception:
message = traceback.format_exception(*sys.exc_info())
logger.error(message)
return self.result(environ, start_response, server_env,(False, "Cannot find the OP! Please view your configuration of pyoidc RP."))
try:
cis = client.construct_AuthorizationRequest(
request_args=request_args)
logger.debug("request: %s" % cis)
url, body, ht_args, cis = client.uri_and_body(
AuthorizationRequest, cis, method="GET",
request_args=request_args)
logger.debug("body: %s" % body)
except Exception:
message = traceback.format_exception(*sys.exc_info())
logger.error(message)
return self.result(environ, start_response, server_env,(False, "Authorization request can not be performed!"))
logger.info("URL: %s" % url)
logger.debug("ht_args: %s" % ht_args)
#session.setAuthn_auth(client.authorization_endpoint)
#session.setAuthentication("VERIFY")
#server_env["CACHE"][sid] = session
session.setClient(client)
resp_headers = [("Location", str(url))]
if ht_args:
resp_headers.extend([(a, b) for a, b in ht_args.items()])
logger.debug("resp_headers: %s" % resp_headers)
start_response("302 Found", resp_headers)
return []
示例9: _format_multiple_exceptions
def _format_multiple_exceptions(e, debug=False):
valid_excs = []
excs = list(e.args)
while excs:
(etype, value, tb) = excs.pop(0)
if (etype == fixtures.MultipleExceptions):
excs.extend(value.args)
elif (etype == fixtures.SetupError):
continue
else:
valid_excs.append((etype, value, tb))
if len(valid_excs) == 1:
(etype, value, tb) = valid_excs[0]
if debug:
LOG.error("".join(traceback.format_exception(etype, value, tb)))
else:
raise value
else:
LOG.error("MultipleExceptions raised:")
for n, (etype, value, tb) in enumerate(valid_excs):
if debug:
LOG.error("- exception %d:" % n)
LOG.error("".join(
traceback.format_exception(etype, value, tb)))
else:
LOG.error(value)
示例10: log_output
def log_output(session, path, args, outfile, uploadpath, cwd=None, logerror=0, append=0, chroot=None, env=None):
"""Run command with output redirected. If chroot is not None, chroot to the directory specified
before running the command."""
pid = os.fork()
fd = None
if not pid:
session._forget()
try:
if chroot:
os.chroot(chroot)
if cwd:
os.chdir(cwd)
flags = os.O_CREAT | os.O_WRONLY
if append:
flags |= os.O_APPEND
fd = os.open(outfile, flags, 0666)
os.dup2(fd, 1)
if logerror:
os.dup2(fd, 2)
# echo the command we're running into the logfile
os.write(fd, '$ %s\n' % ' '.join(args))
environ = os.environ.copy()
if env:
environ.update(env)
os.execvpe(path, args, environ)
except:
msg = ''.join(traceback.format_exception(*sys.exc_info()))
if fd:
try:
os.write(fd, msg)
os.close(fd)
except:
pass
print msg
os._exit(1)
else:
if chroot:
outfile = os.path.normpath(chroot + outfile)
outfd = None
remotename = os.path.basename(outfile)
while True:
status = os.waitpid(pid, os.WNOHANG)
time.sleep(1)
if not outfd:
try:
outfd = file(outfile, 'r')
except IOError:
# will happen if the forked process has not created the logfile yet
continue
except:
print 'Error reading log file: %s' % outfile
print ''.join(traceback.format_exception(*sys.exc_info()))
incremental_upload(session, remotename, outfd, uploadpath)
if status[0] != 0:
if outfd:
outfd.close()
return status[1]
示例11: rateAnalysis
def rateAnalysis(request):
if request.method == 'POST':
print request.POST
try:
user = User.objects.get(id=request.POST['user_id'])
teacher = TeacherProfile.objects.get(user=user)
sa = StandardAnalysis.objects.get(id = request.POST['id'])
sar, created = StandardAnalysisRating.objects.get_or_create(standard_analysis=sa, rater=teacher, rating_type='All')
except:
print traceback.format_exception(*sys.exc_info())
return HttpResponseRedirect('/standard/?standard_id='+str(sa.id))
new_rating = int(request.POST['rating'])
try:
if created:
sar.rating = new_rating
sar.save()
sa.cumulative_rating = (sa.cumulative_rating*sa.number_raters + sar.rating)/(sa.number_raters+1)
sa.number_raters+=1
sa.save()
elif (sar.rating != new_rating):
sa.cumulative_rating = (sa.cumulative_rating*sa.number_raters - sar.rating + new_rating)/sa.number_raters
sar.rating = new_rating
sar.save()
sa.save()
except:
print traceback.format_exception(*sys.exc_info())
return HttpResponse(str(sa.cumulative_rating))
示例12: import_function
def import_function(import_str):
"""
Attempts to import the specified class method or regular function,
and returns a callable.
:raises ImportError if the specified import_str cannot be found.
:raises TypeError if the specified import_str is found but is
not a callable.
"""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
fn = getattr(sys.modules[mod_str], class_str)
if not callable(fn):
msg = '{0} is not callable'
LOG.error(msg)
raise TypeError(msg)
except (ValueError, AttributeError):
msg = 'Method or function {0} cannot be found.'.format(import_str)
err_details = traceback.format_exception(*sys.exc_info())
LOG.error(msg + ' Details: (%s)'.format(err_details))
raise ImportError(msg)
except ImportError:
msg = 'Module {0} cannot be found.'.format(import_str)
err_details = traceback.format_exception(*sys.exc_info())
LOG.error(msg + ' Details: (%s)'.format(err_details))
raise
return fn
示例13: record_results
def record_results(self, resid, uutid):
import os, commands
import string
import traceback
#if environment variable IDTYPE == UUID, then use UUID for database entry id, else implicit auto-increment integer is used.
tmp = self.dbRes[uutid]
self.info("%s" % (tmp))
if (("IDTYPE" in os.environ.keys()) and (os.environ["IDTYPE"]=="UUID")):
try:
database.VssdVg1a1Sweep(
id = (commands.getoutput('uuidgen -t')).strip(),
TestResultsID = resid,
**tmp
)
except:
self.info("An error was thrown: %s"
% string.join(traceback.format_exception(*sys.exc_info()),
''))
else:
try:
database.VssdVg1a1Sweep(
TestResultsID = resid,
**tmp
)
except:
self.info("An error was thrown: %s"
% string.join(traceback.format_exception(*sys.exc_info()),
''))
示例14: __init__
def __init__(self, device=None, config_path=None, user_path=".", cmd_line=""):
"""
Create an option object and check that parameters are valid.
:param device: The device to use
:type device: str
:param config_path: The openzwave config directory. If None, try to configure automatically.
:type config_path: str
:param user_path: The user directory
:type user_path: str
:param cmd_line: The "command line" options of the openzwave library
:type cmd_line: str
"""
try:
if os.path.exists(device):
if os.access(device, os.R_OK) and os.access(device, os.W_OK):
self._device = device
else:
import sys, traceback
raise ZWaveException("Can't write to device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
else:
import sys, traceback
raise ZWaveException("Can't find device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
except:
import sys, traceback
raise ZWaveException("Error when retrieving device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
libopenzwave.PyOptions.__init__(self, config_path=config_path, user_path=user_path, cmd_line=cmd_line)
self._user_path = user_path
self._config_path = config_path
示例15: format
def format(self, record):
"""Formatting function
@param object record: :logging.LogRecord:
"""
entry = {
'name': record.name,
'timestamp': self.formatTime(record,
datefmt="%Y-%m-%d %H:%M:%S"),
'level': record.levelname
}
if hasattr(record, 'message'):
entry['message'] = record.message
else:
entry['message'] = super().format(record)
# add exception information if available
if record.exc_info is not None:
entry['exception'] = {
'message': traceback.format_exception(
*record.exc_info)[-1][:-1],
'traceback': traceback.format_exception(
*record.exc_info)[:-1]
}
return entry