[英]Python functions in exec() not being added to globals/locals dict
我正在使用 python 的exec()
function。我正在嘗試導入一個模塊並定義一個在一個exec()
調用中使用該模塊的 function,然后從另一個exec()
調用中調用該 function。
像這樣:
code1 = "import time
def foo(i):
time.sleep(1)
print(i)"
code2 = "foo('hello')"
custom_globals, custom_locals = {}, {}
exec(code1, custom_globals, custom_locals)
exec(code2, custom_globals, custom_locals)
但是,當我運行這段代碼時,出現錯誤name 'time' is not defined
。 這真的很令人困惑,因為如果我執行以下任一操作:
code2
time.sleep(1)
print(i)
(沒有time
調用) 該腳本將執行而不會出錯。 我對exec()
有什么誤解嗎? 我知道導入的模塊存儲在globals/locals
中,但我想我不太確定方法。 我在這里做錯了什么?
編輯:在第一次exec()
調用后, custom_globals
有它的默認值, custom_locals
看起來像這樣: {'time': <module 'time' (built-in)>, 'foo': <function foo at 0xa159968c0>}
@juanpa.arrivillaga的解決方案是只使用一個 vars dict 而不是一個global
dict 和一個local
dict,因為“如果 exec 獲得兩個單獨的對象作為全局變量和局部變量,代碼將被執行,就好像它被嵌入到 class定義。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.