当前位置: 首页>>代码示例>>Python>>正文


Python inspect.findsource方法代码示例

本文整理汇总了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 
开发者ID:pytest-dev,项目名称:py,代码行数:27,代码来源:test_source.py

示例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 
开发者ID:draios,项目名称:python-sdc-client,代码行数:20,代码来源:conf.py

示例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 
开发者ID:pyx-project,项目名称:pyx,代码行数:21,代码来源:conf.py

示例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 
开发者ID:hydpy-dev,项目名称:hydpy,代码行数:20,代码来源:autodoctools.py

示例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():" 
开发者ID:pytest-dev,项目名称:pytest,代码行数:22,代码来源:test_source.py

示例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()
        } 
开发者ID:romanvm,项目名称:python-web-pdb,代码行数:24,代码来源:__init__.py

示例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
# 
开发者ID:pytest-dev,项目名称:py,代码行数:31,代码来源:source.py

示例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 
开发者ID:pytest-dev,项目名称:py,代码行数:12,代码来源:source.py

示例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():' 
开发者ID:pytest-dev,项目名称:py,代码行数:7,代码来源:test_source.py

示例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():" 
开发者ID:pytest-dev,项目名称:py,代码行数:17,代码来源:test_source.py

示例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:]) 
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:13,代码来源:manage.py

示例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) 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:28,代码来源:pdbpp.py

示例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
# 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:35,代码来源:source.py

示例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 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:10,代码来源:source.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:5,代码来源:test_inspect.py


注:本文中的inspect.findsource方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。