本文整理汇总了Python中inspect.getframeinfo方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getframeinfo方法的具体用法?Python inspect.getframeinfo怎么用?Python inspect.getframeinfo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getframeinfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _format_traceback_frame
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def _format_traceback_frame(self, io, tb): # type: (IO, ...) -> Tuple[Any]
frame_info = inspect.getframeinfo(tb)
filename = frame_info.filename
lineno = frame_info.lineno
function = frame_info.function
line = frame_info.code_context[0]
stripped_line = line.lstrip(" ")
try:
tree = ast.parse(stripped_line, mode="exec")
formatted = self._format_tree(tree, stripped_line, io)
formatted = (len(line) - len(stripped_line)) * " " + formatted
except SyntaxError:
formatted = line
return (
io.format("<c1>{}</c1>".format(filename)),
"<fg=blue;options=bold>{}</>".format(lineno) if not PY2 else lineno,
"<b>{}</b>".format(function),
formatted,
)
示例2: _format
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def _format(self, obj, descend=True):
"""Return a string representation of a single object."""
if inspect.isframe(obj):
filename, lineno, func, context, index = inspect.getframeinfo(obj)
return "<frame of function '%s'>" % func
if not descend:
return self.peek(repr(obj))
if isinstance(obj, dict):
return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False),
self._format(v, descend=False))
for k, v in obj.items()]) + '}'
elif isinstance(obj, list):
return '[' + ', '.join([self._format(item, descend=False)
for item in obj]) + ']'
elif isinstance(obj, tuple):
return '(' + ', '.join([self._format(item, descend=False)
for item in obj]) + ')'
r = self.peek(repr(obj))
if isinstance(obj, (str, int, float)):
return r
return '%s: %s' % (type(obj), r)
示例3: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def __init__(self):
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
dependencies_json = "{}/../resources/builds.json".format(path)
if not os.path.exists(dependencies_json):
raise ValueError("Not found config file '{}'. Try running 'mvn initialize'".format(dependencies_json))
builds = json.load(open(dependencies_json))["builds"]
# prepares resource: version -> namespace -> python package
self.builds = {}
for build in builds:
self.builds[build["version"]] = {}
for package in build["packages"]:
namespace = package["package"]
_module = DependencyManager.get_python_module(package)
self.builds[build["version"]][namespace] = _module
示例4: _called_from_setup
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def _called_from_setup(run_frame):
"""
Attempt to detect whether run() was called from setup() or by another
command. If called by setup(), the parent caller will be the
'run_command' method in 'distutils.dist', and *its* caller will be
the 'run_commands' method. If called any other way, the
immediate caller *might* be 'run_command', but it won't have been
called by 'run_commands'. Return True in that case or if a call stack
is unavailable. Return False otherwise.
"""
if run_frame is None:
msg = "Call stack not available. bdist_* commands may fail."
warnings.warn(msg)
if platform.python_implementation() == 'IronPython':
msg = "For best results, pass -X:Frames to enable call stack."
warnings.warn(msg)
return True
res = inspect.getouterframes(run_frame)[2]
caller, = res[:1]
info = inspect.getframeinfo(caller)
caller_module = caller.f_globals.get('__name__', '')
return (
caller_module == 'distutils.dist'
and info.function == 'run_commands'
)
示例5: _traceback_line
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def _traceback_line(self):
frame = self._frame
if frame is None and self._generator is not None:
frame = debug.get_frame(self._generator)
if frame is not None:
frame_info = inspect.getframeinfo(frame)
template = """File "%(file)s", line %(lineno)s, in %(funcname)s
%(codeline)s"""
return template % {
"file": frame_info.filename,
"lineno": frame_info.lineno,
"funcname": frame_info.function,
"codeline": "\n".join(frame_info.code_context).strip(),
}
else:
return str(self)
示例6: mock_async_callable
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def mock_async_callable(
target,
method,
callable_returns_coroutine=False,
allow_private=False,
type_validation=True,
):
caller_frame = inspect.currentframe().f_back
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
caller_frame_info = inspect.getframeinfo(caller_frame, context=0)
return _MockAsyncCallableDSL(
target,
method,
caller_frame_info,
callable_returns_coroutine,
allow_private,
type_validation,
)
示例7: _get_caller
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def _get_caller(self, depth):
# Doing inspect.stack will retrieve the whole stack, including context
# and that is really slow, this only retrieves the minimum, and does
# not read the file contents.
caller_frame = self._get_caller_frame(depth)
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
frameinfo = inspect.getframeinfo(caller_frame, context=0)
filename = frameinfo.filename
lineno = frameinfo.lineno
if self.TRIM_PATH_PREFIX:
split = filename.split(self.TRIM_PATH_PREFIX)
if len(split) == 2 and not split[0]:
filename = split[1]
if os.path.exists(filename):
return "{}:{}".format(filename, lineno)
else:
return None
示例8: launch_lsh_calc
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def launch_lsh_calc(self):
# store tweets and kick off run_lsh
tw_from = self.cursor
tw_till = len(self.tweets)
dui = ndb.Key(urlsafe = self.duik).get()
dui = dui.extend_tweets(self.tweets[tw_from:tw_till])
self.cursor = len(self.tweets)
if not self.matrix:
Matrix._initialize()
MatrixRow._initialize()
self.matrix = Matrix.create(filename = dui.filename(), source = 'tweets', file_key = self.duik)
if self.matrix:
dui = dui.set_ds_key(self.matrix.ds_key)
if self.matrix:
timestamp = datetime.datetime.utcnow().isoformat()
deferred.defer(run_lsh, self.duik, self.tweets[tw_from:tw_till], self.matrix.ds_key, tw_from, timestamp)
else:
frameinfo = getframeinfo(currentframe())
logging.error('file %s, line %s Matrix is missing', frameinfo.filename, frameinfo.lineno+1)
示例9: findCaller
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def findCaller(
self, stack_info=False, stack_level=1
): # pylint: disable=arguments-differ,unused-argument
"""Find the caller for the current log event.
Args:
stack_info (bool, optional): Defaults to False.
Returns:
tuple: The caller stack information.
"""
caller = None
depth = 3
while True:
# search for the correct calling method
caller = getframeinfo(stack()[depth][0])
if caller.function != 'trace' or depth >= 6:
break
depth += 1
return (caller.filename, caller.lineno, caller.function, None)
示例10: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def __init__(self, **kwargs):
# TODO This is a good first cut for debugging info, but it would be nice to
# TODO be able to reliably walk the stack back to user code rather than just
# TODO back past this constructor
super(DebugInfo, self).__init__(**kwargs)
frame = None
try:
frame = inspect.currentframe()
while frame.f_locals.get('self', None) is self:
frame = frame.f_back
while frame:
filename, lineno, function, code_context, index = inspect.getframeinfo(
frame)
if -1 == filename.find('ngraph/op_graph'):
break
frame = frame.f_back
self.filename = filename
self.lineno = lineno
self.code_context = code_context
finally:
del frame
示例11: __set_message
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def __set_message(self, args, kargs):
details = ', '.join(map(str, args))
errno = kargs['errno'] if 'errno' in kargs and kargs['errno'] else \
self.default_errno
self.errno = errno
message = kargs['message'] if 'message' in kargs and kargs['message'] \
else self.default_msg
exception = ''
if 'frame' in kargs and kargs['frame']:
frame = kargs['frame']
else:
my_frames = inspect.getouterframes(inspect.currentframe())[2]
frame = inspect.getframeinfo(my_frames[0])
if 'exception' in kargs and kargs['exception']:
message = kargs['exception']
elif details:
exception = details
self.frame = frame
self.message = self.message_format % (errno, message, exception,
frame.filename, frame.lineno)
示例12: test_log_info
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def test_log_info(self, logger):
"""
``log_info`` encodes module, function, and line number in the
message_type, and passes other keyword arguments onto the message
structure.
"""
frame = getframeinfo(currentframe())
log_info(key='VAL')
line_no = frame.lineno + 1
self.assertThat(
logger.messages,
AnyMatch(
_dict_values_match(
message_type=ContainsAll(
[__name__, u'test_log_info', unicode(line_no)]),
key=Equals('VAL')
)
)
)
示例13: test_log_error
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def test_log_error(self, logger):
"""
``log_error`` encodes module, function, and line number in the
message_type, and passes other keyword arguments onto the message
structure.
"""
frame = getframeinfo(currentframe())
log_error(key='VAL')
line_no = frame.lineno + 1
self.assertThat(
logger.messages,
AnyMatch(
_dict_values_match(
message_type=ContainsAll(
[__name__, u'test_log_error', unicode(line_no)]),
key=Equals('VAL')
)
)
)
示例14: add_count
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def add_count(self, name, inc=1, prefix=0):
"""
Adds a given value to a named "counter"-type accumulator.
Parameters
----------
name : string
The name of the counter to add `val` into (if the name doesn't exist,
one is created and initialized to `val`).
inc : int, optional
The increment (the value to add to the counter).
prefix : int, optional
Prefix to the timer name the current stack depth and this number
of function names, starting with the current function and moving
the call stack. When zero, no prefix is added. For example,
with `prefix == 1`, "Total" might map to " 3: myFunc: Total".
Returns
-------
None
"""
if prefix > 0:
stack = _inspect.stack()
try:
depth = len(stack) - 1 # -1 to discount current fn (add_count)
functions = " : ".join(_inspect.getframeinfo(frm[0]).filename
for frm in reversed(stack[1:1 + prefix]))
name = "%2d: %s: %s" % (depth, functions, name)
finally:
stack = None # make sure frames get cleaned up properly
if name in self.counters:
self.counters[name] += inc
else:
self.counters[name] = inc
示例15: __str__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getframeinfo [as 别名]
def __str__(self):
"""
Defines how a Label is printed out, e.g. Gx:0 or Gcnot:1:2
"""
#caller = inspect.getframeinfo(inspect.currentframe().f_back)
#ky = "%s:%s:%d" % (caller[2],os.path.basename(caller[0]),caller[1])
#debug_record[ky] = debug_record.get(ky, 0) + 1
s = str(self.name)
if self.sslbls: # test for None and len == 0
s += ":" + ":".join(map(str, self.sslbls))
if self.time != 0.0:
s += ("!%f" % self.time).rstrip('0').rstrip('.')
return s