Python中的AST操作

4

我希望能够修改函数的AST,仅仅是为了娱乐和教学目的,以更改应该打印出来的字符串。

现在经过一些实验,我认为像这样的东西应该可以工作,但即使没有错误,第二个函数也从未打印任何内容。

你有什么想法?我错过了什么吗? (第二个函数应该只打印'world',而不是'hello world'。)

def function_hello():
    print('hello world')


def remove_hello():
    import ast
    import inspect
    source = inspect.getsource(function_hello)
    ast_tree = ast.parse(source)
    st = ast_tree.body[0].body[0].value.args[0]
    st.s = st.s.replace('hello ', '')
    return compile(ast_tree, __file__, mode='exec')


if __name__ == '__main__':
    function_hello()
    exec(remove_hello())

你可以直接修改源代码并编译。 - Padraic Cunningham
1个回答

4
执行编译后的代码将覆盖函数function_hello(而不是调用它)。您需要调用function_hello()来查看您想要的内容。
if __name__ == '__main__':
    function_hello()
    exec(remove_hello())  # This does not call the function.
    function_hello()  # <-----------

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接