如何“重新导入”模块到python然后在导入后更改代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4111640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to "reimport" module to python then code be changed after import
提问by user478514
I have a foo.py
我有一个 foo.py
def foo():
print "test"
In IPython I use:
在 IPython 中,我使用:
In [6]: import foo
In [7]: foo.foo()
test
Then I changed the foo()to:
然后我将其更改foo()为:
def foo():
print "test changed"
In IPython, the result for invoking is still test:
在 IPython 中,调用的结果仍然是test:
In [10]: import foo
In [11]: foo.foo()
test
Then I use:
然后我使用:
In [15]: del foo
In [16]: import foo
In [17]: foo.foo()
test
I delete the foo.pycin same folder foo.pyexists, but still no luck.
我删除了foo.pyc同一个文件夹中的foo.py存在,但仍然没有运气。
May I know how to reimport the updated code in runtime?
我可以知道如何在运行时重新导入更新的代码吗?
采纳答案by John La Rooy
For Python 2.x
对于 Python 2.x
reload(foo)
For Python 3.x
对于 Python 3.x
import importlib
import foo #import the module here, so that it can be reloaded.
importlib.reload(foo)
回答by danlei
In addition to gnibbler's answer:
除了 gnibbler 的回答:
This changed in Python 3 to:
这在 Python 3 中更改为:
>>> import imp
>>> imp.reload(foo)
As @onnodb points out, impis deprecated in favor of importlibsince Python 3.4:
正如@onnodb 所指出的,自 Python 3.4 起imp已被弃用importlib:
>>> import importlib
>>> importlib.reload(foo)
回答by CpILL
If you want this to happen automatically, there is the autoreloadmodule that comes with iPython.
如果您希望这自动发生,则可以使用 iPython 附带的autoreload模块。
回答by Ashfaq
IPython3's autoreloadfeature works just right.
IPython3的自动重载功能效果恰到好处。
I am using the actual example from the webpage. First load the 'autoreload' feature.
我正在使用网页中的实际示例。首先加载“自动重载”功能。
In []: %load_ext autoreload
In []: %autoreload 2
Then import the module you want to test:
然后导入要测试的模块:
In []: import foo
In []: foo.some_function()
Out[]: 42
Open foo.py in an editor and change some_function to return 43
在编辑器中打开 foo.py 并将 some_function 更改为返回 43
In []: foo.some_function()
Out[]: 43
It also works if you import the function directly.
如果您直接导入函数,它也可以工作。
In []: from foo import some_function
In []: some_function()
Out[]: 42
Make change in some_function to return 43.
在 some_function 中进行更改以返回 43。
In []: some_function()
Out[]: 43

