为什么此重新加载失败并显示“ NameError:未定义名称<xxx>”?

时间:2019-07-21 15:45:24

标签: python python-3.x python-module sys

文件:foo_module.py

#file: attempt1.py
import sys
from time import sleep
from importlib import reload
import foo_module  # <-- import the entire module

print(sys.modules['foo_module']) #Lets see if the module is loaded
while True:
    foo_module.foo()

    #simulate a delay or a condition by when foo_module would have changed
    sleep(2)

    #should reload foo_module to get the latest
    reload(foo_module)

文件:try1.py

<module 'foo_module' from 'D:\\pyth\\foo_module.py'>
Am foo v1
Am foo v1
Am foo v1 # I go in around this time and change the foo_module print statement to simulate update to a loaded module
Am foo v2 # Voila ! reload works !
Am foo v2
Am foo v2

输出:

#file: attempt2.py
import sys
from time import sleep
from importlib import reload
from foo_module import foo  # <-- import specific item only

#Lets see if the module is loaded
print(sys.modules['foo_module']) 

while True:
    foo()

    #simulate a delay or a condition by when foo_module would have changed
    sleep(2)

    #try to reload foo_module to get the latest
    reload(foo_module) #FAILS !

这很好,并且按我的预期工作。 但是以下方法不起作用!

文件:try2.py

<module 'foo_module' from 'D:/pyth\\foo_module.py'>  # <-- Module is loaded. isnt it ?
Am foo v1
Traceback (most recent call last):
  File "D:/pyth/attempt2.py", line 10, in <module>
    reload(foo_module)
NameError: name 'foo_module' is not defined

输出:

path

但是在两种情况下sys.modules似乎都包含foo_module的条目! 我想念什么?

1 个答案:

答案 0 :(得分:1)

贷记https://stackoverflow.com/a/46814062/237105

# Reload via sys.modules as it is not imported directly
reload(sys.modules['foo_module'])
# Then, reimport function
from foo_module import foo

您的总代码,已固定:

import sys
from time import sleep
from importlib import reload
from foo_module import foo  # <-- import specific item only

print(sys.modules['foo_module'])
while True:
    foo()

    # simulate a delay or a condition by when foo_module would have changed
    sleep(2)

    # reload foo_module via sys.modules as it is not imported directly
    reload(sys.modules['foo_module'])

    # re-import foo to update it.
    from foo_module import foo