Python中的AST操作
我想做一个有趣的实验,学习一下如何修改一个函数的抽象语法树(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())
1 个回答
4
运行编译好的代码会覆盖掉这个函数 function_hello
(并不是在调用它)。你需要去调用一下 function_hello()
,这样才能看到你想要的结果。
if __name__ == '__main__':
function_hello()
exec(remove_hello()) # This does not call the function.
function_hello() # <-----------