本文整理汇总了Python中inspect.findsource方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.findsource方法的具体用法?Python inspect.findsource怎么用?Python inspect.findsource使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.findsource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_getfslineno
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def test_getfslineno():
from py.code import getfslineno
def f(x):
pass
fspath, lineno = getfslineno(f)
assert fspath.basename == "test_source.py"
assert lineno == py.code.getrawcode(f).co_firstlineno-1 # see findsource
class A(object):
pass
fspath, lineno = getfslineno(A)
_, A_lineno = inspect.findsource(A)
assert fspath.basename == "test_source.py"
assert lineno == A_lineno
assert getfslineno(3) == ("", -1)
class B:
pass
B.__name__ = "B2"
assert getfslineno(B)[1] == -1
示例2: linkcode_resolve
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def linkcode_resolve(domain, info):
def find_line():
obj = sys.modules[info['module']]
for part in info['fullname'].split('.'):
obj = getattr(obj, part)
import inspect
fn = inspect.getsourcefile(obj)
source, lineno = inspect.findsource(obj)
return lineno + 1
if domain != 'py' or not info['module']:
return None
#tag = 'master' if 'dev' in release else ('v' + release)
url = "https://github.com/draios/python-sdc-client/blob/master/sdcclient/_client.py"
try:
return url + '#L%d' % find_line()
except Exception:
return url
示例3: unprocessed_function_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def unprocessed_function_signature(app, what, name, obj, options, sig, retann):
# extract the unprocessed signature from the source
if what not in ["class", "method", "staticmethod", "function"]:
return
if what == "class":
# get the constructor (code copied from autodoc)
obj = getattr(obj, "__init__", None)
if obj is None or obj is object.__init__ or not \
(inspect.ismethod(obj) or inspect.isfunction(obj)):
return
elif hasattr(obj, '__wrapped__'):
obj = obj.__wrapped__
src, line = inspect.findsource(obj)
code = " ".join(function_signature_lines(src[line:])).split("(", 1)[1][:-2]
if code.startswith("self, "):
code = code[6:]
elif code == "self":
code = ""
return "({})".format(code), retann
示例4: _number_of_line
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def _number_of_line(member_tuple):
"""Try to return the number of the first line of the definition of a
member of a module."""
member = member_tuple[1]
try:
return member.__code__.co_firstlineno
except AttributeError:
pass
try:
return inspect.findsource(member)[1]
except BaseException:
pass
for value in vars(member).values():
try:
return value.__code__.co_firstlineno
except AttributeError:
pass
return 0
示例5: test_findsource
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def test_findsource(monkeypatch) -> None:
from _pytest._code.source import findsource
filename = "<pytest-test_findsource>"
lines = ["if 1:\n", " def x():\n", " pass\n"]
co = compile("".join(lines), filename, "exec")
# Type ignored because linecache.cache is private.
monkeypatch.setitem(linecache.cache, filename, (1, None, lines, filename)) # type: ignore[attr-defined]
src, lineno = findsource(co)
assert src is not None
assert "if 1:" in str(src)
d = {} # type: Dict[str, Any]
eval(co, d)
src, lineno = findsource(d["x"])
assert src is not None
assert "if 1:" in str(src)
assert src[lineno] == " def x():"
示例6: get_current_frame_data
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def get_current_frame_data(self):
"""
Get all date about the current execution frame
:return: current frame data
:rtype: dict
:raises AttributeError: if the debugger does hold any execution frame.
:raises IOError: if source code for the current execution frame is not accessible.
"""
filename = self.curframe.f_code.co_filename
lines, start_line = inspect.findsource(self.curframe)
if sys.version_info[0] == 2:
lines = [line.decode('utf-8') for line in lines]
return {
'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep,
'filename': os.path.basename(filename),
'file_listing': ''.join(lines),
'current_line': self.curframe.f_lineno,
'breakpoints': self.get_file_breaks(filename),
'globals': self.get_globals(),
'locals': self.get_locals()
}
示例7: getfslineno
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def getfslineno(obj):
""" Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1)
"""
try:
code = py.code.Code(obj)
except TypeError:
try:
fn = (inspect.getsourcefile(obj) or
inspect.getfile(obj))
except TypeError:
return "", -1
fspath = fn and py.path.local(fn) or None
lineno = -1
if fspath:
try:
_, lineno = findsource(obj)
except IOError:
pass
else:
fspath = code.path
lineno = code.firstlineno
assert isinstance(lineno, int)
return fspath, lineno
#
# helper functions
#
示例8: findsource
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def findsource(obj):
try:
sourcelines, lineno = inspect.findsource(obj)
except py.builtin._sysex:
raise
except:
return None, -1
source = Source()
source.lines = [line.rstrip() for line in sourcelines]
return source, lineno
示例9: test_findsource_fallback
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def test_findsource_fallback():
from py._code.source import findsource
src, lineno = findsource(x)
assert 'test_findsource_simple' in str(src)
assert src[lineno] == ' def x():'
示例10: test_findsource
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def test_findsource():
from py._code.source import findsource
co = py.code.compile("""if 1:
def x():
pass
""")
src, lineno = findsource(co)
assert 'if 1:' in str(src)
d = {}
eval(co, d)
src, lineno = findsource(d['x'])
assert 'if 1:' in str(src)
assert src[lineno] == " def x():"
示例11: call_func
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def call_func(args):
print("Looking for function callable with params: '{}'".format(args))
fname = args[0]
farr = load_functions()
if not fname in farr:
return False
print("Function signature: '%s'" % (inspect.getsourcelines(farr[fname])[0][0].strip(), ))
print("Found function %s, from file %s, line %s" % (farr[fname], inspect.getsourcefile(farr[fname]), inspect.findsource(farr[fname])[1]))
return try_call(farr[fname], args[1:])
示例12: _printlonglist
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def _printlonglist(self, linerange=None, max_lines=None):
try:
if self.curframe.f_code.co_name == '<module>':
# inspect.getsourcelines is buggy in this case: if we just
# pass the frame, it returns the source for the first function
# defined in the module. Instead, we want the full source
# code of the module
lines, _ = inspect.findsource(self.curframe)
lineno = 1
else:
try:
lines, lineno = inspect.getsourcelines(self.curframe)
except Exception as e:
print('** Error in inspect.getsourcelines: %s **' %
e, file=self.stdout)
return
except IOError as e:
print('** Error: %s **' % e, file=self.stdout)
return
if linerange:
start, end = linerange
start = max(start, lineno)
end = min(end, lineno+len(lines))
lines = lines[start-lineno:end-lineno]
lineno = start
self._print_lines_pdbpp(lines, lineno, max_lines=max_lines)
示例13: getfslineno
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def getfslineno(obj):
""" Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1).
The line number is 0-based.
"""
from .code import Code
try:
code = Code(obj)
except TypeError:
try:
fn = inspect.getsourcefile(obj) or inspect.getfile(obj)
except TypeError:
return "", -1
fspath = fn and py.path.local(fn) or None
lineno = -1
if fspath:
try:
_, lineno = findsource(obj)
except IOError:
pass
else:
fspath = code.path
lineno = code.firstlineno
assert isinstance(lineno, int)
return fspath, lineno
#
# helper functions
#
示例14: findsource
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def findsource(obj):
try:
sourcelines, lineno = inspect.findsource(obj)
except Exception:
return None, -1
source = Source()
source.lines = [line.rstrip() for line in sourcelines]
return source, lineno
示例15: test_findsource_binary
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import findsource [as 别名]
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)