python中,reload重新加载module

一般来说用一下代码就可reload你的module

from importlib import reload
reload(YourModule)

如果你开始写的是下面的,想重新加载,

from YourModule import *

需要用下面几句:

1 import YourModule # to get a module object
2 reload(YourModule) # to reload the module
3 from YourModule import * # to reimport all public names

或者

1 from importlib import reload
2 import sys
3 
4 mod = reload(sys.modules['YourModule'])#use imp.reload for Python 3
5 vars().update(mod.__dict__) #update the global namespace

具体解释可见:

how to reload after “from <module> import *”?

When you do from module import * everything from that module is fetched into the current namespace and at the end the reference to module is removed. But, due to module caching the module object can still be accessed from sys.modules, so that in case you do some more import later one than it doesn't have to fetch the module again.

That said, one way to do what you're expecting is:

import sys
from foo import * print A, B #prints 1, 2 A, B = 100, 200 mod = reload(sys.modules['foo'])#use imp.reload for Python 3 vars().update(mod.__dict__) #update the global namespace print A, B #prints 1, 2

As a side note, using import * is usually frowned upon:

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

猜你喜欢

转载自www.cnblogs.com/andy-0212/p/10069057.html