[英]Python define and call function represented by string
假設我們有一個字符串
function_string = 'def main():\n\treturn(1)'
如何在運行時將其編譯為函數然后執行?
這是我目前的嘗試,不幸的是它引發了一個 NameError 表示未定義main
:
self.run():
exec(self.formatted_function_string) # similar to 'function_string' in the example
print(main())
正如我在評論中所說,執行/評估任意字符串是一種安全風險。 但是如果你真的想這樣做,你需要向exec
傳遞一個適當的全局字典。 這里的自然選擇是將globals()
dict 傳遞給它,以便您的exec
定義的任何名稱都放入全局命名空間。
def test(argstring):
exec(argstring, globals())
print(main())
function_string = 'def main():\n\treturn(1)'
test(function_string)
print(main)
典型輸出
1
<function main at 0xb7196cd4>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.