问题描述
以下代码抛出异常:
import inspect
def work():
my_function_code = """def print_hello():
print('Hi!')
"""
exec(my_function_code, globals())
inspect.getsource(print_hello)
上面的代码抛出异常 IOError.如果我在不使用 exec 的情况下声明函数(如下所示),我可以获得它的源代码就好了.
The code above throws an exception IOError. If I declare the function without using exec (like below), I can get its source code just fine.
import inspect
def work():
def print_hello():
print('Hi!')
inspect.getsource(print_hello)
我有充分的理由做这样的事情.
There's a good reason for me to do something like this.
是否有解决方法?有可能做这样的事情吗?如果没有,为什么?
Is there a workaround for this? Is it possible to do something like this? If not, why?
推荐答案
我刚看了inspect.py 阅读@jsbueno 的回答后的文件,这是我发现的:
I just looked at the inspect.py file after reading @jsbueno's answer, here's what I found :
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
的情况下是不可能的.
It clearly indicates that it tries to open the source file and then reads its content, which is why it is not possible in case of exec
.
这篇关于无法获得“声明"的方法的源代码;通过 exec 在 Python 中使用检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!