本文整理汇总了Python中traceback.extract_stack方法的典型用法代码示例。如果您正苦于以下问题:Python traceback.extract_stack方法的具体用法?Python traceback.extract_stack怎么用?Python traceback.extract_stack使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类traceback
的用法示例。
在下文中一共展示了traceback.extract_stack方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: breakpoint
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def breakpoint(output, vars=None, cond=lambda v: True, grad=True):
tb = tuple(traceback.extract_stack()[:-1])
py_vars = {}
if type(vars) not in (tuple, list, dict, types.NoneType):
raise ValueError('vars keyword arg must be None, dict, list or tuple')
if not isinstance(vars, dict):
frame_locals = inspect.stack()[1][0].f_locals
if vars is not None:
frame_locals = dict((name, val)
for (name, val) in frame_locals.iteritems()
if name in vars or val in vars)
vars = frame_locals
assert isinstance(vars, dict)
th_vars = dict((name, val) for (name, val) in vars.iteritems()
if isinstance(val, _theano_types))
py_vars = dict((name, val) for (name, val) in vars.iteritems()
if name not in th_vars)
(th_var_names, th_var_vals) = zip(*th_vars.iteritems())
return Breakpoint(th_var_names, cond, tb, py_vars, grad) \
(output, *th_var_vals)
示例2: worker_int
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def worker_int(worker):
worker.log.info("worker received INT or QUIT signal")
# get traceback info
import threading
import sys
import traceback
id2name = {th.ident: th.name for th in threading.enumerate()}
code = []
for threadId, stack in list(sys._current_frames().items()):
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId, ""), threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
worker.log.debug("\n".join(code))
示例3: format_callstack
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def format_callstack():
""" Format the callstack to find out the stack trace. """
ind = 0
for ind, frame in enumerate(f[0] for f in inspect.stack()):
if "__name__" not in frame.f_globals:
continue
modname = frame.f_globals["__name__"].split(".")[0]
if modname != "logging":
break
def _format_frame(frame):
""" Format the frame. """
return ' File "%s", line %i in %s\n %s' % (frame)
stack = traceback.extract_stack()
stack = stack[:-ind]
return "\n".join([_format_frame(frame) for frame in stack])
示例4: HasShape
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def HasShape(tensor, expected_shape, ndims=None):
"""Syntactic sugar for asserting that tensor has the expected shape.
Args:
tensor: A Tensor.
expected_shape: A Python list or a 1D tensor.
ndims: If not None, check only the first `ndims` dimensions of `tensor`.
Must be equal to the length of `expected_shape` if not None.
Returns:
The input `tensor`
Raises:
A runtime error if the assertion fails.
"""
if _FromGlobal('enable_asserts'):
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
msg = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(r'.*/', '',
filepath), line, func)
return with_dependencies([
ops.assert_shape_match(
tf.shape(tensor)[:ndims], expected_shape, msg=msg)
], tensor)
else:
return tensor
示例5: test_top_bottom
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def test_top_bottom():
def a():
b()
def b():
c()
def c():
set_trace()
return
check(
a, """
[NUM] > .*c()
-> return
5 frames hidden .*
# top
[ 0] > .*()
-> .*
# bottom
[{stack_len}] > .*c()
-> return
# c
""".format(stack_len=len(traceback.extract_stack())))
示例6: test_do_bt
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def test_do_bt():
def fn():
set_trace()
expected_bt = []
for i, entry in enumerate(traceback.extract_stack()[:-3]):
expected_bt.append(" [%2d] .*" % i)
expected_bt.append(" .*")
check(fn, r"""
--Return--
[NUM] > .*fn()->None
-> set_trace()
5 frames hidden .*
# bt
{expected}
[NUM] .*(NUM)runpdb()
func()
> [NUM] .*(NUM)fn()->None
set_trace()
# c
""".format(expected="\n".join(expected_bt)))
示例7: test_do_bt_highlight
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def test_do_bt_highlight():
def fn():
set_trace(Config=ConfigWithHighlight)
expected_bt = []
for i, entry in enumerate(traceback.extract_stack()[:-3]):
expected_bt.append(" [%2d] .*" % i)
expected_bt.append(" .*")
check(fn, r"""
--Return--
[NUM] > .*fn()->None
-> set_trace(Config=ConfigWithHighlight)
5 frames hidden .*
# bt
{expected}
[NUM] ^[[33;01m.*\.py^[[00m(^[[36;01mNUM^[[00m)runpdb()
func()
> [NUM] ^[[33;01m.*\.py^[[00m(^[[36;01mNUM^[[00m)fn()->None
set_trace(Config=ConfigWithHighlight)
# c
""".format(expected="\n".join(expected_bt)))
示例8: test_do_bt_pygments
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def test_do_bt_pygments():
def fn():
set_trace(Config=ConfigWithPygments)
expected_bt = []
for i, entry in enumerate(traceback.extract_stack()[:-3]):
expected_bt.append(" [%2d] .*" % i)
expected_bt.append(" .*")
check(fn, r"""
--Return--
[NUM] > .*fn()->None
-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)
5 frames hidden .*
# bt
{expected}
[NUM] .*(NUM)runpdb()
func()
> [NUM] .*\.py(NUM)fn()->None
set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)
# c
""".format(expected="\n".join(expected_bt)))
示例9: find_deepest_user_frame
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def find_deepest_user_frame(tb):
"""
Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack()
"""
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0]
示例10: caller_trace
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def caller_trace(back=0):
"""
Trace caller stack and save info into global dicts, which
are printed automatically at the end of SCons execution.
"""
global caller_bases, caller_dicts
import traceback
tb = traceback.extract_stack(limit=3+back)
tb.reverse()
callee = tb[1][:3]
caller_bases[callee] = caller_bases.get(callee, 0) + 1
for caller in tb[2:]:
caller = callee + caller[:3]
try:
entry = caller_dicts[callee]
except KeyError:
caller_dicts[callee] = entry = {}
entry[caller] = entry.get(caller, 0) + 1
callee = caller
# print a single caller and its callers, if any
示例11: register
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def register(self, candidate, name=None):
"""Registers a Python object "candidate" for the given "name".
Args:
candidate: The candidate object to add to the registry.
name: An optional string specifying the registry key for the candidate.
If None, candidate.__name__ will be used.
Raises:
KeyError: If same name is used twice.
"""
if not name:
name = candidate.__name__
if name in self._registry:
(filename, line_number, function_name, _) = (
self._registry[name][_LOCATION_TAG])
raise KeyError("Registering two %s with name '%s' !"
"(Previous registration was in %s %s:%d)" %
(self._name, name, function_name, filename, line_number))
logging.vlog(1, "Registering %s (%s) in %s.", name, candidate, self._name)
# stack trace is [this_function, Register(), user_function,...]
# so the user function is #2.
stack = traceback.extract_stack()
self._registry[name] = {_TYPE_TAG: candidate, _LOCATION_TAG: stack[2]}
示例12: doTraceback
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def doTraceback(self, module):
try:
module.do_raise()
except:
tb = sys.exc_info()[2].tb_next
f,lno,n,line = extract_tb(tb, 1)[0]
self.assertEqual(line, raise_src.strip())
f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
self.assertEqual(line, raise_src.strip())
s = StringIO.StringIO()
print_tb(tb, 1, s)
self.assertTrue(s.getvalue().endswith(raise_src))
else:
raise AssertionError("This ought to be impossible")
示例13: thunk_hook
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def thunk_hook(type, value, trace):
"""
WRITEME
This function is meant to replace excepthook and do some
special work if the exception value has a __thunk_trace__
field. In that case, it retrieves the field, which should
contain a trace as returned by L{traceback.extract_stack},
and prints it out on L{stderr}.
The normal excepthook is then called.
Notes
-----
This hook replaced by nosetests, so it does not run in nose tests.
"""
log_thunk_trace(value)
__excepthook(type, value, trace)
示例14: caller_trace
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def caller_trace(back=0):
import traceback
tb = traceback.extract_stack(limit=3+back)
tb.reverse()
callee = tb[1][:3]
caller_bases[callee] = caller_bases.get(callee, 0) + 1
for caller in tb[2:]:
caller = callee + caller[:3]
try:
entry = caller_dicts[callee]
except KeyError:
caller_dicts[callee] = entry = {}
entry[caller] = entry.get(caller, 0) + 1
callee = caller
# print a single caller and its callers, if any
示例15: worker_int
# 需要导入模块: import traceback [as 别名]
# 或者: from traceback import extract_stack [as 别名]
def worker_int(worker):
worker.log.info("worker received INT or QUIT signal")
## get traceback info
import threading, sys, traceback
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId, ""),
threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename,
lineno, name))
if line:
code.append(" %s" % (line.strip()))
worker.log.debug("\n".join(code))