[英]How do I reload a python submodule?
I'm loading a submodule in python (2.7.10) with from app import sub
where sub
has a config
variable.我正在使用
from app import sub
在 python (2.7.10)中加载一个子模块,其中sub
有一个config
变量。 So I can run print sub.config
and see a bunch of config variables.所以我可以运行
print sub.config
并查看一堆配置变量。 Not super complex.不是超级复杂。
If I change the config variables in the script, there must be a way to reload the module and see the change.如果我更改脚本中的配置变量,必须有办法重新加载模块并查看更改。 I found a few instructions that indicated that
reload(app.sub)
would work, but I get an error:我发现一些说明表明
reload(app.sub)
可以工作,但我收到一个错误:
NameError: name 'app' is not defined
And if I do just reload(sub)
the error is:如果我只是
reload(sub)
错误是:
TypeError: reload() argument must be module
If I do import app
I can view the config with print app.sub.config
and reload with reload(app)
如果我确实
import app
,我可以使用print app.sub.config
查看配置并使用reload(app)
重新加载
-- if I do import app
and then run -- 如果我确实
import app
然后运行
I found instructions to automate reloading: Reloading submodules in IPython我找到了自动重新加载的说明: Reloading submodules in IPython
but is there no way to reload a submodule manually?但是有没有办法手动重新加载子模块?
When you from foo import bar
, you now have a module object named bar
in your namespace, so you can 当你
from foo import bar
,你现在在你的命名空间中有一个名为bar
的模块对象,所以你可以
from foo import bar
bar.do_the_thing() # or whatever
reload(bar)
If you want some more details on how different import forms work, I personally found this answer particularly helpful, myself. 如果您想了解有关不同导入表单的工作方式的更多详细信息,我个人认为这个答案特别有用,我自己。
With python3,I try this: 使用python3,我试试这个:
import importlib
import sys
def m_reload():
for k,v in sys.modules.items():
if k.startswith('your-package-name'):
importlib.reload(v)
from importlib import reload
import sys
ls=[]
#making copy to avoid regeneration of sys.modules
for i,j in sys.modules.items():
r,v=i,j
ls.append((r,v))
for i in ls:
if i[0] == 'my_library_name':
reload(i[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.