我希望能够修改函数的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())