How to compile a string of Python code into a module whose functions can be called?

后端 未结 2 1996
悲哀的现实
悲哀的现实 2021-02-05 21:13

In Python, I have a string of some Python source code containing functions like:

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

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


        
2条回答
  •  野的像风
    2021-02-05 21:49

    In Python 2, you want the magical compiler package:

    >>> 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))))])
    

    And in Python 3, it's built right in.

提交回复
热议问题