无法使用 Python 中的检查通过 exec 获取“声明”的方法的源代码

2024-01-09

下面的代码抛出异常:

import inspect

def work():
    my_function_code = """def print_hello():
                              print('Hi!')
                       """
    exec(my_function_code, globals())
    inspect.getsource(print_hello)

上面的代码抛出异常 IOError。如果我在不使用 exec 的情况下声明该函数(如下所示),我可以很好地获取其源代码。

import inspect

def work():
    def print_hello():
        print('Hi!')
    inspect.getsource(print_hello)

我有充分的理由做这样的事情。

有解决方法吗?可以做这样的事情吗?如果没有,为什么?


我刚刚看了检查.py http://www.opensource.apple.com/source/python/python-3/python/Lib/inspect.py阅读@jsbueno的答案后的文件,这是我发现的:

def findsource(object):
    """Return the entire source file and starting line number for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of all the lines
    in the file and the line number indexes a line in that list.  An **IOError
    is raised if the source code cannot be retrieved.**"""
    try:
        file = open(getsourcefile(object))  
    except (TypeError, IOError):
        raise IOError, 'could not get source code'
    lines = file.readlines()               #reads the file
    file.close()

它清楚地表明它尝试打开源文件然后读取其内容,这就是为什么在以下情况下这是不可能的exec.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用 Python 中的检查通过 exec 获取“声明”的方法的源代码 的相关文章

随机推荐