15

在 Python 中,我有一串 Python 源代码,其中包含以下函数:

mySrc = '''
def foo():
    print("foo")

def bar():
    print("bar")
'''

我想把这个字符串编译成某种类似模块的对象,这样我就可以调用代码中包含的函数。

这是我想做的伪代码:

myMod = myCompile(mySrc)
myMod.foo()

这在 Python 中可能吗?我试过这个,但它不起作用:

myMod = compile(mySrc, '', 'exec')
myMod.foo()

这会产生如下错误消息:

<code object <module> at 0x104154730, file "", line 1>Traceback (most recent call last):
  File "myfile.py", line XX, in run
    myMod.foo()
AttributeError: 'code' object has no attribute 'foo'
4

2 回答 2

22

您必须编译和执行它:

myMod = compile(mySrc, '', 'exec')
exec(myMod)
foo()

您可以通过 dicts 来exec阻止foo“泄漏”。将它与使用创建的模块对象结合types.ModuleType

from types import ModuleType
…
compiled = compile(mySrc, '', 'exec')
module = ModuleType("testmodule")
exec(compiled, module.__dict__)
于 2013-11-08T01:49:03.227 回答
1

在 Python 2 中,您需要神奇的编译器包

>>> import compiler
>>> mod = compiler.parseFile("doublelib.py")
>>> mod
Module('This is an example module.\n\nThis is the docstring.\n',
       Stmt([Function(None, 'double', ['x'], [], 0,
                      'Return twice the argument',
                      Stmt([Return(Mul((Name('x'), Const(2))))]))]))
>>> from compiler.ast import *
>>> Module('This is an example module.\n\nThis is the docstring.\n',
...    Stmt([Function(None, 'double', ['x'], [], 0,
...                   'Return twice the argument',
...                   Stmt([Return(Mul((Name('x'), Const(2))))]))]))
Module('This is an example module.\n\nThis is the docstring.\n',
       Stmt([Function(None, 'double', ['x'], [], 0,
                      'Return twice the argument',
                      Stmt([Return(Mul((Name('x'), Const(2))))]))]))
>>> mod.doc
'This is an example module.\n\nThis is the docstring.\n'
>>> for node in mod.node.nodes:
...     print node
...
Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
         Stmt([Return(Mul((Name('x'), Const(2))))]))
>>> func = mod.node.nodes[0]
>>> func.code
Stmt([Return(Mul((Name('x'), Const(2))))])

在 Python 3 中,它直接内置在.

于 2013-11-08T01:53:51.517 回答