2

我希望能夠(僅用於娛樂和教學目的)修改函數的AST,以便更改應打印出的字符串。Python中的AST操作

現在經過一些實驗,我認爲像這樣的東西應該可以工作,但即使沒有錯誤,第二個函數也不會打印任何東西。

任何關於我失蹤的想法? (第二個函數應該只是打印「世界」而不是「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()) 
+0

你可以改變源代碼並編譯它。 –

回答

2

執行編譯的代碼覆蓋功能function_hello(不調用它)。你需要撥打function_hello()看看你想要什麼。

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

真棒是的,這是問題,謝謝! –