本文整理汇总了Python中inspect.html方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.html方法的具体用法?Python inspect.html怎么用?Python inspect.html使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.html方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: normalize_call_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def normalize_call_args(call_args, func=None, signature=None, with_defaults=True):
if func is None and signature is None:
raise ValueError("Must supply either func or signature")
if func is not None and signature is not None:
raise ValueError("Must supply either func or signature; not both")
if signature is None:
signature = inspect.signature(func)
args, kwargs = call_args
bound_args = signature.bind(*args, **kwargs)
# based on code from the Python docs:
# https://docs.python.org/3/library/inspect.html#inspect.BoundArguments
if with_defaults:
for param in signature.parameters.values():
if (
param.name not in bound_args.arguments
and param.default is not param.empty
):
bound_args.arguments[param.name] = param.default
return bound_args.args, bound_args.kwargs
示例2: caller_name
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def caller_name(depth=1):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
stack = inspect.stack()
start = 0 + depth
if len(stack) < start + 1:
return ''
parentframe = stack[start][0]
path = get_frame_path(parentframe)
## Avoid circular refs and frame leaks
# https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
del parentframe, stack
return path
示例3: get_python_file_from_previous_stack_frame
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def get_python_file_from_previous_stack_frame():
'''inspect.stack() lets us introspect the call stack; inspect.stack()[1] is the previous
stack frame.
In Python < 3.5, this is just a tuple, of which the python file of the previous frame is the 1st
element.
In Python 3.5+, this is a FrameInfo namedtuple instance; the python file of the previous frame
remains the 1st element.
'''
# Since this is now a function in this file, we need to go back two hops to find the
# callsite file.
previous_stack_frame = inspect.stack(0)[2]
# See: https://docs.python.org/3/library/inspect.html
if sys.version_info.major == 3 and sys.version_info.minor >= 5:
check.inst(previous_stack_frame, inspect.FrameInfo)
else:
check.inst(previous_stack_frame, tuple)
python_file = previous_stack_frame[1]
return os.path.abspath(python_file)
示例4: _inspect_func_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def _inspect_func_args(fn):
try:
co_varkeywords = inspect.CO_VARKEYWORDS
except AttributeError:
# https://docs.python.org/3/library/inspect.html
# The flags are specific to CPython, and may not be defined in other
# Python implementations. Furthermore, the flags are an implementation
# detail, and can be removed or deprecated in future Python releases.
spec = compat.inspect_getfullargspec(fn)
return spec[0], bool(spec[2])
else:
# use fn.__code__ plus flags to reduce method call overhead
co = fn.__code__
nargs = co.co_argcount
return (
list(co.co_varnames[:nargs]),
bool(co.co_flags & co_varkeywords),
)
示例5: add
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def add(self, *args, **kwargs):
default = kwargs.get('default')
dtype = kwargs.get('type')
if dtype is None:
if default is None:
dtype = str
else:
dtype = type(default)
typename = dtype.__name__
if 'metavar' not in kwargs:
# metavar: display --foo <float=0.05> in help string
if 'choices' in kwargs:
choices = kwargs['choices']
choices_str = '/'.join(['{}']*len(choices)).format(*choices)
kwargs['metavar'] = '<{}: {}>'.format(typename, choices_str)
elif 'nargs' in kwargs:
# better formatting handled in _SingleMetavarFormatter
kwargs['metavar'] = '{}'.format(typename)
elif not kwargs.get('action'):
# if 'store_true', then no metavar needed
# list of actions: https://docs.python.org/3/library/argparse.html#action
default_str = '={}'.format(default) if default else ''
kwargs['metavar'] = '<{}{}>'.format(typename, default_str)
self.parser.add_argument(*args, **kwargs)
示例6: post_cv_match
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def post_cv_match(self, cv_ret, *args, **kwargs):
if not cv_ret:
return
# 如果当前函数是由loop_find调用的,那就可以找到一个rect,这个rect由airtest.core.cv._cv_match里给出
# 以下就是从frame stack中一直找到loop_find这一帧,然后找出loop_find的第一个argument,通过argument求出tid
frame = sys._getframe(0)
while frame and frame.f_code.co_name != 'loop_find':
frame = frame.f_back
if frame:
# more details about inspect parameter name in runtime,
# see https://docs.python.org/2/library/inspect.html#inspect.getargvalues
args, varargs, keywords, locals = inspect.getargvalues(frame)
if len(args) > 0:
v_name = args[0]
elif varargs is not None and len(locals[varargs]) > 0:
v_name = locals[varargs][0]
else:
raise ValueError('loop_find第一个参数不支持使用keyword args')
# 取到loop_find的第一个argument
v = locals[v_name]
tid = id(v)
rect = cv_ret.get("rectangle")
if rect:
# a rect's each vertex in screen as following
# [0] [3]
# [1] [2]
t = rect[0][1] * 1.0
r = rect[3][0] * 1.0
b = rect[1][1] * 1.0
l = rect[0][0] * 1.0
w, h = current_device().getCurrentScreenResolution()
self.action_recorder.bounding(tid, [t / h, r / w, b / h, l / w])
示例7: trim_docstring
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def trim_docstring(docstring):
# Cleans up whitespaces from an indented docstring
#
# See https://www.python.org/dev/peps/pep-0257/
# and https://docs.python.org/2/library/inspect.html#inspect.cleandoc
return inspect.cleandoc(docstring) if docstring else None
示例8: group
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def group(s, n):
# See
# http://www.python.org/doc/2.6/library/functions.html#zip
return zip(*[iter(s)]*n)
示例9: interleave_planes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def interleave_planes(ipixels, apixels, ipsize, apsize):
"""
Interleave (colour) planes, e.g. RGB + A = RGBA.
Return an array of pixels consisting of the `ipsize` elements of data
from each pixel in `ipixels` followed by the `apsize` elements of data
from each pixel in `apixels`. Conventionally `ipixels` and
`apixels` are byte arrays so the sizes are bytes, but it actually
works with any arrays of the same type. The returned array is the
same type as the input arrays which should be the same type as each other.
"""
itotal = len(ipixels)
atotal = len(apixels)
newtotal = itotal + atotal
newpsize = ipsize + apsize
# Set up the output buffer
# See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
out = array(ipixels.typecode)
# It's annoying that there is no cheap way to set the array size :-(
out.extend(ipixels)
out.extend(apixels)
# Interleave in the pixel data
for i in range(ipsize):
out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
for i in range(apsize):
out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
return out
示例10: mycallersname
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def mycallersname():
"""Returns the name of the caller of the caller of this function
(hence the name of the caller of the function in which
"mycallersname()" textually appears). Returns None if this cannot
be determined."""
# http://docs.python.org/library/inspect.html#the-interpreter-stack
import inspect
frame = inspect.currentframe()
if not frame:
return None
frame_,filename_,lineno_,funname,linelist_,listi_ = (
inspect.getouterframes(frame)[2])
return funname
示例11: _enhex
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def _enhex(s):
"""Convert from binary string (bytes) to hex string (str)."""
import binascii
return bytestostr(binascii.hexlify(s))
# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter.
示例12: group
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def group(s, n):
# See
# http://www.python.org/doc/2.6/library/functions.html#zip
return list(zip(*[iter(s)]*n))
示例13: set_preprocess_fn
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def set_preprocess_fn(self, preprocess_fn): # pytype: disable=invalid-annotation
"""Register the preprocess_fn used during the input data generation.
Note, the preprocess_fn can only have `features` and optionally `labels` as
inputs. The `mode` has to be abstracted by using a closure or
functools.partial prior to passing a preprocessor.preprocess function.
For example using functools:
set_preprocess_fn(
functools.partial(preprocessor.preprocess,
mode=tf.estimator.ModeKeys.TRAIN))
Args:
preprocess_fn: The function called during the input dataset generation to
preprocess the data.
"""
if isinstance(preprocess_fn, functools.partial): # pytype: disable=wrong-arg-types
# Note, we do not combine both conditions into one since
# inspect.getargspec does not work for functools.partial objects.
if 'mode' not in preprocess_fn.keywords:
raise ValueError('The preprocess_fn mode has to be set if a partial'
'function has been passed.')
else:
if six.PY3:
argspec = inspect.getfullargspec(preprocess_fn)
# first 4 element of fullspec corresponds to spec:
# https://docs.python.org/3.4/library/inspect.html
argspec = inspect.ArgSpec(*argspec[:4])
else:
argspec = inspect.getargspec(preprocess_fn) # pylint: disable=deprecated-method
if 'mode' in argspec.args:
raise ValueError('The passed preprocess_fn has an open argument `mode`'
'which should be patched by a closure or with '
'functools.partial.')
self._preprocess_fn = preprocess_fn
示例14: get_metadata
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def get_metadata(type):
metadata = dict()
if hasattr(type, 'from_urdf'):
metadata['from_urdf'] = getattr(type, 'from_urdf')
else:
if sys.version_info[0] < 3:
argspec = inspect.getargspec(type.__init__) # this is deprecated in python3
else:
argspec = inspect.getfullargspec(type.__init__)
args = {}
required = len(argspec.args)
if argspec.defaults:
required -= len(argspec.defaults)
for i in range(1, len(argspec.args)):
data = dict(required=i < required)
default_index = i - required
if default_index >= 0:
default = argspec.defaults[default_index]
data['default'] = default
data['sequence'] = hasattr(default, '__iter__')
else:
data['sequence'] = False
args[argspec.args[i]] = data
if sys.version_info[0] < 3:
metadata['keywords'] = argspec.keywords is not None
else:
# TODO: make sure replacing keyword with kwonlyargs is correct, check at: https://docs.python.org/3/library/inspect.html#inspect.getargspec
metadata['keywords'] = argspec.kwonlyargs is not None
metadata['init_args'] = args
metadata['argument_map'] = getattr(type, 'argument_map', {})
return metadata
示例15: _get_bound_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import html [as 别名]
def _get_bound_args(func, *args, **kwargs):
"""
https://docs.python.org/3/library/inspect.html#inspect.BoundArguments
def f(a, b, c=5, d=6): pass
get_bound_args(f, 3, 6, d=100) -> {'a':3, 'b':6, 'c':5, 'd':100}
Returns:
OrderedDict of bound arguments
"""
arginfo = inspect.signature(func).bind(*args, **kwargs)
arginfo.apply_defaults()
return arginfo.arguments