本文整理汇总了Python中traceback.format_exception函数的典型用法代码示例。如果您正苦于以下问题:Python format_exception函数的具体用法?Python format_exception怎么用?Python format_exception使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_exception函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:informatics-isi-edu,项目名称:microscopy,代码行数:29,代码来源:update_slide_label_annotation.py
示例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
开发者ID:teerytko,项目名称:nokiantorpedo-django,代码行数:34,代码来源:feedjack_update.py
示例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)
开发者ID:7modelsan,项目名称:kbengine,代码行数:26,代码来源:result.py
示例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)),
)
)
开发者ID:facebook,项目名称:watchman,代码行数:26,代码来源:runtests.py
示例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 }} )
开发者ID:swarbhanu,项目名称:coi-services,代码行数:34,代码来源:service_gateway_service.py
示例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
开发者ID:chyileon,项目名称:iie_leon,代码行数:27,代码来源:service_thread.py
示例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:
开发者ID:project-renard-survey,项目名称:xerox-parc-uplib-mirror,代码行数:33,代码来源:startAngel.py
示例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 []
开发者ID:hdknr,项目名称:pyoidc,代码行数:60,代码来源:__init__.py
示例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)
开发者ID:felixonmars,项目名称:pifpaf,代码行数:27,代码来源:__main__.py
示例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]
开发者ID:ccoss,项目名称:koji,代码行数:60,代码来源:daemon.py
示例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))
开发者ID:arn0601,项目名称:lessnlab,代码行数:28,代码来源:views.py
示例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
开发者ID:MiquelCollado,项目名称:talons,代码行数:28,代码来源:helpers.py
示例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()),
''))
开发者ID:pruan,项目名称:TestDepot,代码行数:28,代码来源:VssdVg1a1Sweep.py
示例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
开发者ID:JshWright,项目名称:python-openzwave,代码行数:30,代码来源:option.py
示例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
开发者ID:a-stark,项目名称:qudi,代码行数:25,代码来源:logger.py
示例16: send
def send(self, service_name, method, *args):
import openerp
import traceback
import xmlrpclib
try:
result = openerp.netsvc.dispatch_rpc(service_name, method, args)
except Exception,e:
# TODO change the except to raise LibException instead of their emulated xmlrpc fault
if isinstance(e, openerp.osv.osv.except_osv):
fault = xmlrpclib.Fault('warning -- ' + e.name + '\n\n' + e.value, '')
elif isinstance(e, openerp.exceptions.Warning):
fault = xmlrpclib.Fault('warning -- Warning\n\n' + str(e), '')
elif isinstance(e, openerp.exceptions.AccessError):
fault = xmlrpclib.Fault('warning -- AccessError\n\n' + str(e), '')
elif isinstance(e, openerp.exceptions.AccessDenied):
fault = xmlrpclib.Fault('AccessDenied', str(e))
elif isinstance(e, openerp.exceptions.DeferredException):
info = e.traceback
formatted_info = "".join(traceback.format_exception(*info))
fault = xmlrpclib.Fault(openerp.tools.ustr(e.message), formatted_info)
else:
info = sys.exc_info()
formatted_info = "".join(traceback.format_exception(*info))
fault = xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info)
raise fault
开发者ID:CloudWareChile,项目名称:OpenChile,代码行数:25,代码来源:http.py
示例17: main
def main():
# Initialize color support
colorama.init()
try:
run()
except util.DeviceException as e:
typ, val, tb = sys.exc_info()
logging.debug("".join(traceback.format_exception(typ, val, tb)))
print(colorama.Fore.RED + "There is a problem with your device"
" configuration:")
print(colorama.Fore.RED + e.message)
except ConfigError as e:
typ, val, tb = sys.exc_info()
logging.debug("".join(traceback.format_exception(typ, val, tb)))
print(colorama.Fore.RED +
"There is a problem with your configuration file(s):")
print(colorama.Fore.RED + e.message)
except util.MissingDependencyException as e:
typ, val, tb = sys.exc_info()
logging.debug("".join(traceback.format_exception(typ, val, tb)))
print(colorama.Fore.RED +
"You are missing a dependency for one of your enabled plugins:")
print(colorama.Fore.RED + e.message)
except KeyboardInterrupt:
colorama.deinit()
sys.exit(1)
except Exception as e:
typ, val, tb = sys.exc_info()
print(colorama.Fore.RED + "spreads encountered an error:")
print(colorama.Fore.RED +
"".join(traceback.format_exception(typ, val, tb)))
# Deinitialize color support
colorama.deinit()
开发者ID:5up3rD4n1,项目名称:spreads,代码行数:33,代码来源:main.py
示例18: makeVideoThumb
def makeVideoThumb(fullPath, thumbPath):
print "\n", 80*"-", "\ncreating video thumbnail with command: "
# must create two frames because of mplayer bug
createCmd = MPLAYER_DIR+" -vo jpeg -quiet -frames 2 -ss 5 "+ fullPath
print createCmd
try:
sp.check_call(createCmd.split())
except:
print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
# delete one of them
try:
os.remove("00000001.jpg")
except:
print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
# resize it to 300x300
try:
im = wx.Image("00000002.jpg") # read the original image
if im.Ok(): #the image may be corrupted...
im.Rescale(300, 300) # resize it
im.SaveFile("00000002.jpg", wx.BITMAP_TYPE_JPEG) # save it back to a file
except:
print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
# rename the right one
try:
shutil.move("00000002.jpg", thumbPath)
except:
print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
开发者ID:MattHung,项目名称:sage-graphics,代码行数:30,代码来源:makeThumbs.py
示例19: MachineMachine
def MachineMachine():
LATTICE = "star" ##, 'diamond'
DIMENSION = (5, 11)
PLAYERS = "a", "b", " "
##mc = Mangorona(PLAYERS,'cubic', DIMENSION, None)
##maximum=True
##getall=True
mc = Mangorona(PLAYERS, "diamond", (7, 11), None)
maximum = True
getall = False
t = PLAYERS[:2]
tab = 0
print(Board(mc).Display())
while True:
try:
turn = t[tab % 2]
movable = AllowableMovement(mc, turn).Move(maximum=maximum, getall=getall)
machine = random.choice(movable)
print(turn, "move:", machine[0], machine[1])
mc.Move(turn, machine[0], machine[1])
print(Board(mc).Display())
print(mc.gain["a"], mc.gain["b"]) ##, t1-t0
print()
tab += 1
except IllegalMove:
exc = traceback.format_exception(*sys.exc_info())[-1]
print(exc)
except NoMoreMove:
exc = traceback.format_exception(*sys.exc_info())[-1]
print(exc)
print("winner:", mc.Winner())
break
开发者ID:nirinA,项目名称:scripts_python,代码行数:32,代码来源:mangorona.py
示例20: OnPaint
def OnPaint(self, event):
namespace = {'self':self, 'event':event, 'wx':wx}
if not self.error and self.codes.get('OnPaint', None):
try:
code = compile((self.codes['OnPaint'].replace('\r\n', '\n') + '\n'), 'canvastest', 'exec')
self.error = False
except:
self.error = True
traceback.format_exception(*sys.exc_info())
def f():
d = wx.lib.dialogs.ScrolledMessageDialog(self.parent, (tr("Error compiling script.\n\nTraceback:\n\n") +
''.join(trace)), tr("Error"), wx.DefaultPosition, wx.Size(400,300))
d.ShowModal()
d.Destroy()
wx.CallAfter(f)
return
try:
exec code in namespace
self.error = False
except:
self.error = True
trace = traceback.format_exception(*sys.exc_info())
def f():
d = wx.lib.dialogs.ScrolledMessageDialog(self.parent, (tr("Error running script.\n\nTraceback:\n\n") +
''.join(trace)), tr("Error"), wx.DefaultPosition, wx.Size(400,300))
d.ShowModal()
d.Destroy()
wx.CallAfter(f)
return
else:
dc = wx.PaintDC(self)
dc.Clear()
event.Skip
开发者ID:LaoMa3953,项目名称:ulipad,代码行数:34,代码来源:CanvasPanel.py
注:本文中的traceback.format_exception函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论