如何在 Python 解释器中重新导入更新的包?

问题描述:

我经常在 Python 解释器中测试我的模块,当我看到错误时,我会迅速更新 .py 文件.但是我如何让它反映在解释器上?所以,到目前为止,我一直在退出并重新进入解释器,因为再次重新导入文件对我不起作用.

I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.

Python3 更新:(引自 已经回答了,因为上次编辑/评论在这里建议了一个不推荐使用的方法)

Update for Python3: (quoted from the already-answered answer, since the last edit/comment here suggested a deprecated method)

在 Python 3 中,reload 已移至 imp 模块.在 3.4 中,imp 被弃用,取而代之的是 importlibreload 被添加到后者.面向 3 或更高版本时,请在调用 reload 时引用适当的模块或导入它.

In Python 3, reload was moved to the imp module. In 3.4, imp was deprecated in favor of importlib, and reload was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload or import it.

外卖:

  • Python3 >= 3.4:importlib.reload(packagename)
  • Python3 <3.4: imp.reload(packagename)
  • Python2:继续往下看

使用 reload 内置函数:

https://docs.python.org/2/library/functions.html#重新​​加载

reload(module)被执行时:

  • 重新编译 Python 模块的代码并重新执行模块级代码,定义一组新的对象,这些对象绑定到模块字典中的名称.扩展模块的 init 函数不会被第二次调用.
  • 与 Python 中的所有其他对象一样,旧对象仅在其引用计数降至零后才会被回收.
  • 更新模块命名空间中的名称以指向任何新的或更改的对象.
  • 对旧对象的其他引用(例如模块外部的名称)不会重新引用以引用新对象,并且必须在每个命名空间中更新(如果需要).

示例:

# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1

# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2