本文整理汇总了Python中traceback.format_list函数的典型用法代码示例。如果您正苦于以下问题:Python format_list函数的具体用法?Python format_list怎么用?Python format_list使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_list函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: TriggerEvent
def TriggerEvent(self, function, args):
"""Triggers an event for the plugins. Since events and notifications
are precisely the same except for how n+ responds to them, both can be
triggered by this function."""
hotpotato = args
for module, plugin in list(self.enabled_plugins.items()):
try:
func = eval("plugin.PLUGIN." + function)
ret = func(*hotpotato)
if ret is not None and type(ret) != tupletype:
if ret == returncode['zap']:
return None
elif ret == returncode['break']:
return hotpotato
elif ret == returncode['pass']:
pass
else:
log.add(_("Plugin %(module)s returned something weird, '%(value)s', ignoring") % {'module': module, 'value': ret})
if ret is not None:
hotpotato = ret
except:
log.add(_("Plugin %(module)s failed with error %(errortype)s: %(error)s.\nTrace: %(trace)s\nProblem area:%(area)s") % {
'module': module,
'errortype': sys.exc_info()[0],
'error': sys.exc_info()[1],
'trace': ''.join(format_list(extract_stack())),
'area': ''.join(format_list(extract_tb(sys.exc_info()[2])))
})
return hotpotato
开发者ID:Nicotine-Plus,项目名称:nicotine-plus,代码行数:29,代码来源:pluginsystem.py
示例2: format_stack_report
def format_stack_report(details, exc_info):
header = ''
header += "Exception\n---------\n"
if exc_info:
header += ''.join(traceback.format_exception(*exc_info))
header += "\n"
# Print out a stack trace too. The exception stack only contains
# calls between the try and the exception.
try:
stack = util.get_nice_stack()
except StandardError:
stack = traceback.extract_stack()
header += "Call Stack\n---------\n"
header += ''.join(traceback.format_list(stack))
header += "\n"
else:
# fake an exception with our call stack
try:
stack = util.get_nice_stack()
except StandardError:
stack = traceback.extract_stack()
header += ''.join(traceback.format_list(stack))
header += 'UnknownError: %s\n' % details
header += "\n"
return header
开发者ID:CodeforEvolution,项目名称:miro,代码行数:25,代码来源:crashreport.py
示例3: log_except
def log_except(*args, **kw):
logger = kw.get('logger', None)
better = kw.pop('_better', 0)
if not logger:
logger = logging.root
if not len(args):
msg = None
elif len(args) == 1:
msg = args[0]
args = []
else:
msg = args[0]
args = args[1:]
lines = ['Traceback (most recent call last):\n']
if better:
import better_exchook
better_exchook.better_exchook(*sys.exc_info(),
output=lambda s:lines.append('%s\n' % s))
else:
ei = sys.exc_info()
st = traceback.extract_stack(f=ei[2].tb_frame.f_back)
et = traceback.extract_tb(ei[2])
lines.extend(traceback.format_list(st))
lines.append(' ****** Traceback ****** \n')
lines.extend(traceback.format_list(et))
lines.extend(traceback.format_exception_only(ei[0], ei[1]))
exc = ''.join(lines)
if msg:
args = list(args)
args.append(exc)
logger.error(msg + ':\n%s', *args)
else:
logger.error(exc)
开发者ID:soulsharepj,项目名称:zdzl,代码行数:34,代码来源:log.py
示例4: LockCheck
def LockCheck():
global semaphores
while 1:
each = None
Sleep(5 * 60)
now = time.time()
try:
for each in semaphores.keys():
BeNice()
if (each.count<=0) and (each.waiting.balance < 0) and (each.lockedWhen and (now - each.lockedWhen)>=(5*MIN)):
logger.error("Semaphore %s appears to have threads in a locking conflict."%id(each))
logger.error("holding thread:")
try:
for s in traceback.format_list(traceback.extract_stack(each.thread.frame,40)):
logger.error(s)
except:
sys.exc_clear()
first = each.waiting.queue
t = first
while t:
logger.error("waiting thread %s:"%id(t),4)
try:
for s in traceback.format_list(traceback.extract_stack(t.frame,40)):
logger.error(s,4)
except:
sys.exc_clear()
t = t.next
if t is first:
break
logger.error("End of locking conflict log")
except StandardError:
StackTrace()
sys.exc_clear()
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:33,代码来源:uthread.py
示例5: __reportLocalError
def __reportLocalError(self, tb_list, class_, func, error):
'''
Create a report of an error while calling a __post_init__ method and the
error is thrown within this module. (class)
Errors are probably argument type errors, so we want to point to the
declaration of the __post_init__ function that generated the exception
:param tb_list: traceback list of the error
:param class_: visited class that produced the error
:param func: method of the class that produced the error
:param error: error (exception) thrown while calling func
'''
tb_list = traceback.format_list(tb_list[:-3])
msg = '\nTraceback: \n'
msg += ''.join(tb_list)
msg += '%s' % error.message
# create traceback friendly report
filename = inspect.getsourcefile(func)
lines, lineno = inspect.getsourcelines(func)
line = lines[0]
name = func.__name__
extracted_list = [(filename, lineno, name, line)]
# Print the report
func_hint = ''.join(traceback.format_list(extracted_list))
msg += '\n\n%s' % (func_hint)
msg += ' Remember that %r \n only accepts keywords arguments in' \
' the constructor.' % class_
return msg
开发者ID:joaduo,项目名称:mepinta2,代码行数:29,代码来源:PostInitStrategyBase.py
示例6: make_hivemap
def make_hivemap(hm, __subcontext__=None, *args, **kwargs):
maphive = build_hivemap(hm)
try:
return maphive(*args, **kwargs).getinstance()
except TypeError as e:
raise # ##TODO
if __subcontext__ is None: raise
import sys, traceback
tb = sys.exc_info()[2]
tbstack = traceback.extract_tb(tb)
tblist = traceback.format_list(tbstack)
raise HivemapTypeError(__subcontext__, tblist, e.args)
except ValueError as e:
raise # ##TODO
if __subcontext__ is None:
raise
import sys, traceback
tb = sys.exc_info()[2]
tbstack = traceback.extract_tb(tb)
tblist = traceback.format_list(tbstack)
raise HivemapValueError(__subcontext__, tblist, e.args)
开发者ID:agoose77,项目名称:hivesystem,代码行数:27,代码来源:hivemaphive.py
示例7: _stack_function_
def _stack_function_(message='', limit=None):
import traceback
stack = traceback.extract_stack()
if stack:
if limit:
logging.debug('%s\n*** %s' % (message, '*** '.join(traceback.format_list(stack[-limit-1:-1]))))
else:
logging.debug('%s\n*** %s' % (message, '*** '.join(traceback.format_list(stack)[0:-1])))
开发者ID:freevo,项目名称:freevo1,代码行数:8,代码来源:config.py
示例8: initiate
def initiate(kickstart_host, base, extra_append, static_device=None, system_record="", preserve_files=[]):
error_messages = {}
success = 0
# cleanup previous attempt
rm_rf(SHADOW)
os.mkdir(SHADOW)
print "Preserve files! : %s" % preserve_files
try:
if static_device:
update_static_device_records(kickstart_host, static_device)
k = Koan()
k.list_items = 0
k.server = kickstart_host
k.is_virt = 0
k.is_replace = 1
k.is_display = 0
k.profile = None
if system_record != "":
k.system = system_record
else:
k.system = None
k.port = 443
k.image = None
k.live_cd = None
k.virt_path = None
k.virt_type = None
k.virt_bridge = None
k.no_gfx = 1
k.add_reinstall_entry = None
k.kopts_override = None
k.use_kexec = None
k.embed_kickstart = None
if hasattr(k, 'no_copy_default'):
k.no_copy_default = 1
else: # older koan
k.grubby_copy_default = 0
if static_device:
k.embed_kickstart = 1
k.run()
except Exception, e:
(xa, xb, tb) = sys.exc_info()
try:
getattr(e,"from_koan")
error_messages['koan'] = str(e)[1:-1]
print str(e)[1:-1] # nice exception, no traceback needed
except:
print xa
print xb
print string.join(traceback.format_list(traceback.extract_tb(tb)))
error_messages['koan'] = string.join(traceback.format_list(traceback.extract_tb(tb)))
return (1, "Kickstart failed. Koan error.", error_messages)
开发者ID:T-D-Oe,项目名称:spacewalk,代码行数:58,代码来源:spacewalkkoan.py
示例9: initiate_guest
def initiate_guest(kickstart_host, cobbler_system_name, virt_type, name, mem_kb,
vcpus, disk_gb, virt_bridge, disk_path, extra_append, log_notify_handler=None):
error_messages = {}
success = 0
try:
if disk_path.startswith('/dev/'):
if not os.path.exists(disk_path):
raise BlockDeviceNonexistentError(disk_path)
else:
if os.path.exists(disk_path):
raise VirtDiskPathExistsError(disk_path)
k = Koan()
k.list_items = 0
k.server = kickstart_host
k.is_virt = 1
k.is_replace = 0
k.is_display = 0
k.port = 443
k.profile = None
k.system = cobbler_system_name
k.should_poll = 1
k.image = None
k.live_cd = None
k.virt_name = name
k.virt_path = disk_path
k.virt_type = virt_type
k.virt_bridge = virt_bridge
k.no_gfx = False
k.add_reinstall_entry = None
k.kopts_override = None
k.virt_auto_boot = None
if hasattr(k, 'no_copy_default'):
k.no_copy_default = 1
else: # older koan
k.grubby_copy_default = 0
if hasattr(k, 'virtinstall_wait'):
k.virtinstall_wait = 0
k.run()
# refresh current virtualization state on the server
import virtualization.support
virtualization.support.refresh()
except Exception, e:
(xa, xb, tb) = sys.exc_info()
if str(xb).startswith("The MAC address you entered is already in use"):
# I really wish there was a better way to check for this
error_messages['koan'] = str(xb)
print str(xb)
elif hasattr(e,"from_koan") and len(str(e)) > 1:
error_messages['koan'] = str(e)[1:-1]
print str(e)[1:-1] # nice exception, no traceback needed
else:
print xa
print xb
print string.join(traceback.format_list(traceback.extract_tb(tb)))
error_messages['koan'] = str(xb) + ' ' + string.join(traceback.format_list(traceback.extract_tb(tb)))
return (1, "Virtual kickstart failed. Koan error.", error_messages)
开发者ID:bsmeets86,项目名称:spacewalk,代码行数:58,代码来源:spacewalkkoan.py
示例10: _limited_traceback
def _limited_traceback(excinfo):
""" Return a formatted traceback with all the stack
from this frame (i.e __file__) up removed
"""
tb = extract_tb(excinfo.tb)
try:
idx = [__file__ in e for e in tb].index(True)
return format_list(tb[idx+1:])
except ValueError:
return format_list(tb)
开发者ID:astronouth7303,项目名称:xonsh,代码行数:10,代码来源:pytest_plugin.py
示例11: configure
def configure(self, beedict):
if not self.bound_target:
from .drone import drone
if isinstance(self.target.instance, drone) and self.target.instance in beedict.values():
self.target = [v for v in beedict if beedict[v] is self.target.instance][0]
else:
self.bind()
n = beedict[self.target]
n = resolve(n, parameters=self.parameters)
if n is self:
raise Exception("bee.configure target '%s' is self" % self.target)
from .worker import workerframe
if isinstance(n, beewrapper):
assert n.instance is not None
n = n.instance
if isinstance(n, workerframe):
assert n.built
n = n.bee
for attrs, stack, args, kargs in self.configuration:
args = tuple([resolve(a, parameters=self.parameters) for a in args])
kargs = dict((a, resolve(kargs[a], parameters=self.parameters)) for a in kargs)
try:
nn = n
setitem = False
for mode, attr in attrs:
if mode == "getattr":
nn = getattr(nn, attr)
elif mode == "getitem":
nn = nn[attr]
elif mode == "setitem":
attr, value = attr
nn[attr] = value
setitem = True
else:
raise Exception(mode) # should never happen
if not setitem:
nn(*args, **kargs)
except Exception as e:
s1 = traceback.format_list(stack[:-1])
tbstack = traceback.extract_tb(sys.exc_info()[2])
s2 = traceback.format_list(tbstack[1:])
s3 = traceback.format_exception_only(type(e), e)
s = "\n" + "".join(s1 + s2 + s3)
raise ConfigureBeeException(s)
if isinstance(n, configure_base):
n.configure()
开发者ID:agoose77,项目名称:hivesystem,代码行数:55,代码来源:configure.py
示例12: __init__
def __init__(self, msg, cause=None):
"""Constructor."""
if (cause != None) and (not isinstance(cause, ChainedException)):
# store stack trace in other Exceptions
exi = sys.exc_info()
if exi != None:
cause.__dict__["stackTrace"] = traceback.format_list(traceback.extract_tb(exi[2]))
Exception.__init__(self, msg)
self.msg = msg
self.cause = cause
self.stackTrace = traceback.format_list(traceback.extract_stack())[0:-1]
开发者ID:melissacline,项目名称:ucscCancer,代码行数:11,代码来源:Exceptions.py
示例13: __init__
def __init__(self, msg, cause=None):
"""Constructor."""
if (cause is not None) and (not isinstance(cause, PycbioException)):
# store stack trace in other Exception types
exi = sys.exc_info()
if exi is not None:
setattr(cause, "stackTrace", traceback.format_list(traceback.extract_tb(exi[2])))
Exception.__init__(self, msg)
self.msg = msg
self.cause = cause
self.stackTrace = traceback.format_list(traceback.extract_stack())[0:-1]
开发者ID:ucsc-mus-strain-cactus,项目名称:Comparative-Annotation-Toolkit,代码行数:11,代码来源:__init__.py
示例14: _limited_traceback
def _limited_traceback(excinfo):
"""Return a formatted traceback with this frame up removed.
The function removes all the stack from this frame up
(i.e from __file__ and up)
"""
tb = extract_tb(excinfo.tb)
try:
idx = [__file__ in e for e in tb].index(True)
return format_list(tb[idx + 1 :])
except ValueError:
return format_list(tb)
开发者ID:AnyBody-Research-Group,项目名称:AnyPyTools,代码行数:12,代码来源:pytest_plugin.py
示例15: get_trace
def get_trace():
trace = sys.exc_info()[2]
if trace:
stack = traceback.extract_tb(trace)
traceback_list = traceback.format_list(stack)
return "".join(traceback_list)
else:
stack = traceback.extract_stack()
traceback_list = traceback.format_list(stack)
return "".join(traceback_list[:-1])
开发者ID:complynx,项目名称:pilot,代码行数:13,代码来源:misc.py
示例16: default_exception_handler
def default_exception_handler(self, context):
"""Default exception handler.
This is called when an exception occurs and no exception
handler is set, and can be called by a custom exception
handler that wants to defer to the default behavior.
The context parameter has the same meaning as in
`call_exception_handler()`.
"""
message = context.get('message')
if not message:
message = 'Unhandled exception in event loop'
exception = context.get('exception')
if exception is not None:
if hasattr(exception, '__traceback__'):
# Python 3
tb = exception.__traceback__
else:
# call_exception_handler() is usually called indirectly
# from an except block. If it's not the case, the traceback
# is undefined...
tb = sys.exc_info()[2]
exc_info = (type(exception), exception, tb)
else:
exc_info = False
if ('source_traceback' not in context
and self._current_handle is not None
and self._current_handle._source_traceback):
context['handle_traceback'] = self._current_handle._source_traceback
log_lines = [message]
for key in sorted(context):
if key in ('message', 'exception'):
continue
value = context[key]
if key == 'source_traceback':
tb = ''.join(traceback.format_list(value))
value = 'Object created at (most recent call last):\n'
value += tb.rstrip()
elif key == 'handle_traceback':
tb = ''.join(traceback.format_list(value))
value = 'Handle created at (most recent call last):\n'
value += tb.rstrip()
else:
value = repr(value)
log_lines.append('{0}: {1}'.format(key, value))
logger.error('\n'.join(log_lines), exc_info=exc_info)
开发者ID:billtsay,项目名称:win-demo-opcua,代码行数:51,代码来源:base_events.py
示例17: __init__
def __init__(self, field, config, msg):
self.fieldType = type(field)
self.fieldName = field.name
self.fullname = _joinNamePath(config._name, field.name)
self.history = config.history.setdefault(field.name, [])
self.fieldSource = field.source
self.configSource = config._source
error="%s '%s' failed validation: %s\n"\
"For more information read the Field definition at:\n%s"\
"And the Config definition at:\n%s"%\
(self.fieldType.__name__, self.fullname, msg,
traceback.format_list([self.fieldSource])[0],
traceback.format_list([self.configSource])[0])
ValueError.__init__(self, error)
开发者ID:jonathansick-shadow,项目名称:pex_config,代码行数:14,代码来源:config.py
示例18: __init__
def __init__ (self, msg, parent=None) :
ptype = type(parent).__name__ # exception type for parent
stype = type(self).__name__ # exception type for self, useful for
# inherited exceptions
# did we get a parent exception?
if parent :
# if so, then this exception is likely created in some 'except'
# clause, as a reaction on a previously catched exception (the
# parent). Thus we append the message of the parent to our own
# message, but keep the parent's traceback (after all, the original
# exception location is what we are interested in).
#
if isinstance (parent, MyEx) :
# that all works nicely when parent is our own exception type...
self.traceback = parent.traceback
frame = traceback.extract_stack ()[-2]
line = "%s +%s (%s) : %s" % frame
self.msg = " %-20s: %s (%s)\n%s" % (stype, msg, line, parent.msg)
else :
# ... but if parent is a native (or any other) exception type,
# we don't have a traceback really -- so we dig it out of
# sys.exc_info.
trace = sys.exc_info ()[2]
stack = traceback.extract_tb (trace)
traceback_list = traceback.format_list (stack)
self.traceback = "".join (traceback_list)
# the message composition is very similar -- we just inject the
# parent exception type inconspicuously somewhere (above that
# was part of 'parent.msg' already).
frame = traceback.extract_stack ()[-2]
line = "%s +%s (%s) : %s" % frame
self.msg = " %-20s: %s (%s)\n %-20s: %s" % (stype, msg, line, ptype, parent)
else :
# if we don't have a parent, we are a 1st principle exception,
# i.e. a reaction to some genuine code error. Thus we extract the
# traceback from exactly where we are in the code (the last stack
# frame will be the call to this exception constructor), and we
# create the original exception message from 'stype' and 'msg'.
stack = traceback.extract_stack ()
traceback_list = traceback.format_list (stack)
self.traceback = "".join (traceback_list[:-1])
self.msg = " %-20s: %s" % (stype, msg)
开发者ID:HumanBrainProject,项目名称:saga-python,代码行数:50,代码来源:exceptions.py
示例19: start_game
def start_game(self, gamekey):
dict_files_to_copy = self.apply_mods(False)
logging.info("start the game")
if self.save_settings() != -1:
# Check to see if folderlocation is valid.
if path.isdir(self.config[SET].get(WF_KEY, "\n\n\n\n\n\n\n\n\n\n\n")):
# TODO: put in try catch block here.
try:
if(sys.platform=='win32'):
subprocess.Popen(path.join(self.config[SET][WF_KEY],gamekey), cwd=self.config[SET][WF_KEY])
if sys.platform.startswith('linux'):
subprocess.Popen("wine " + path.join(self.config[SET][WF_KEY],gamekey), cwd=self.config[SET][WF_KEY])
except OSError:
# ICK. User is on windows an the executable is set to run as administrator.
logging.warning(sys.exc_info()[1])
for line in traceback.format_list(traceback.extract_tb(sys.exc_info()[2])):
logging.warning(line)
logging.info("Using workaround.")
# Use workaround.
game_location = dict_files_to_copy.get(gamekey)
try:
subprocess.Popen(game_location, cwd=self.config[SET][WF_KEY])
except OSError:
logging.warning("OSError error:", sys.exc_info()[0])
logging.warning(sys.exc_info()[1])
for line in traceback.format_list(traceback.extract_tb(sys.exc_info()[2])):
logging.warning(line)
messagebox.showerror(message="OSError: Exe is set to run as administrator. Please uncheck the 'run as admin' in the exe properties.", title='OSError')
except:
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning(sys.exc_info()[1])
for line in traceback.format_list(traceback.extract_tb(sys.exc_info()[2])):
logging.warning(line)
messagebox.showerror(message="Unknown Error", title='Error')
else:
logging.info("No.")
except:
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning(sys.exc_info()[1])
for line in traceback.format_list(traceback.extract_tb(sys.exc_info()[2])):
logging.warning(line)
messagebox.showerror(message="Unknown Error", title='Error')
else:
logging.warning("Invalid directory location")
开发者ID:cmcaine,项目名称:SMAC-Mod-Manager,代码行数:49,代码来源:SMACXLauncher.py
示例20: __str__
def __str__(self):
if self._op is not None:
output = ["%s\n\nCaused by op %r, defined at:\n" % (self.message,
self._op.name,)]
curr_traceback_list = traceback.format_list(self._op.traceback)
output.extend(curr_traceback_list)
# pylint: disable=protected-access
original_op = self._op._original_op
# pylint: enable=protected-access
while original_op is not None:
output.append(
"\n...which was originally created as op %r, defined at:\n"
% (original_op.name,))
prev_traceback_list = curr_traceback_list
curr_traceback_list = traceback.format_list(original_op.traceback)
# Attempt to elide large common subsequences of the subsequent
# stack traces.
#
# TODO(mrry): Consider computing the actual longest common subsequence.
is_eliding = False
elide_count = 0
last_elided_line = None
for line, line_in_prev in zip(curr_traceback_list, prev_traceback_list):
if line == line_in_prev:
if is_eliding:
elide_count += 1
last_elided_line = line
else:
output.append(line)
is_eliding = True
elide_count = 0
else:
if is_eliding:
if elide_count > 0:
output.extend(
["[elided %d identical lines from previous traceback]\n"
% (elide_count - 1,), last_elided_line])
is_eliding = False
output.extend(line)
# pylint: disable=protected-access
original_op = original_op._original_op
# pylint: enable=protected-access
output.append("\n%s (see above for traceback): %s\n" %
(type(self).__name__, self.message))
return "".join(output)
else:
return self.message
开发者ID:AliMiraftab,项目名称:tensorflow,代码行数:49,代码来源:errors_impl.py
注:本文中的traceback.format_list函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论