【发布时间】: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