【问题标题】:AST manipulation in PythonPython中的AST操作
【发布时间】:2014-07-13 15:34:36
【问题描述】:

我希望能够(仅出于娱乐和教学目的)修改函数的 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())

【问题讨论】:

  • 你可以改变源代码并编译它。

标签: python python-3.x compiler-construction abstract-syntax-tree


【解决方案1】:

执行编译后的代码会覆盖函数function_hello(而不是调用它)。你需要打电话给function_hello()看看你想要什么。

if __name__ == '__main__':
    function_hello()
    exec(remove_hello())  # This does not call the function.
    function_hello()  # <-----------

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2016-06-29
    相关资源
    最近更新 更多