我希望能够(只是为了好玩和说教的目的)修改一个函数的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())
最佳答案
执行编译后的代码会覆盖函数function_hello
(不调用它)。你需要打电话给function_hello()
看看你想要什么。
if __name__ == '__main__':
function_hello()
exec(remove_hello()) # This does not call the function.
function_hello() # <-----------