简体   繁体   English

如何检查用exec创建的函数代码

[英]python - How to inspect code of function created with exec

I have a function that was created with exec() inside another function and passed as an argument to the main program. 我有一个在另一个函数中使用exec()创建的函数,并作为参数传递给主程序。 How can I get the code of said function? 我怎样才能获得所述函数的代码? I tried inspec.getsourcelines() and inspec.getsource() but I get the following error 我试过inspec.getsourcelines()inspec.getsource()但是我得到以下错误

IOError: could not get source code

Is there a way around this? 有没有解决的办法?

MWE main file: MWE主文件:

#!/usr/bin/python
from ext import makeF
import inspect

f=makeF()
f()
inspect.getsource(f)

then external file: 然后是外部文件:

def makeF():
    script="def sayA():\n\tprint('Aah')"
    exec(script)
    return sayA

This is not possible. 这是不可能的。 I've been digging around and came to the same conclusion as outlined in this answer . 我一直在挖掘并得出与本答案中概述的相同的结论。

I don't know your code, but I think in your specific case you could return a custom object containing the source code of the function (which you seem to have - you're passing it to exec) together with the actual compiled function. 我不知道您的代码,但我认为在您的具体情况下,您可以返回一个自定义对象,其中包含函数的源代码(您似乎已将其传递给exec)以及实际编译的函数。 You could even leverage Python's __call__ magic method to better emulate the original behaviour. 您甚至可以利用Python的__call__魔术方法来更好地模拟原始行为。 Here's a sample: 这是一个示例:

class FunctionWithCode:
    def __init__(self, source, func_name):
        exec(source)
        self.source = source
        self.func = locals()[func_name]

    def __call__(self, *args, **kwargs):
        self.func(*args, **kwargs)

f = FunctionWithCode("def sayA():\n\tprint('Aah')", 'sayA')

f()

which prints Aah as expected. 按预期打印Aah。 You would need to know the function name when creating the object but this is the same for your sample code. 创建对象时需要知道函数名称,但这与示例代码相同。

In python 3 the solution is the __globals__ attribute of the functions. 在python 3中,解决方案是函数的__globals__属性。

With your example : 用你的例子:

>>> f.__globals__['txt']
"def sayA():\n\tprint('Aah')"

Unfortunately I could not find anything like for Python 2. 不幸的是我找不到像Python 2那样的东西。


The reason why the other methods cannot work, is because they use the filename of the module and here you do not have any file. 其他方法无法工作的原因是因为它们使用模块的文件名而这里没有任何文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM