无法使用Python中的inspect通过exec获取"声明"的方法的源代码

mta*_*med 5 python reflection

以下代码抛出异常:

import inspect

def work():
    my_function_code = """def print_hello():
                              print('Hi!')
                       """
    exec(my_function_code, globals())
    inspect.getsource(print_hello)
Run Code Online (Sandbox Code Playgroud)

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

import inspect

def work():
    def print_hello():
        print('Hi!')
    inspect.getsource(print_hello)
Run Code Online (Sandbox Code Playgroud)

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

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

Ash*_*ary 6

我在阅读了@jsbueno的回答后看了一下inspect.py文件,这是我发现的:

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()
Run Code Online (Sandbox Code Playgroud)

它清楚地表明它试图打开源文件然后读取其内容,这就是为什么它不可能的原因exec.