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

编程入门 行业动态 更新时间:2024-10-27 12:37:23
本文介绍了如何在 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 被弃用,取而代之的是 importlib 和 reload 被添加到后者.面向 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 内置函数:

docs.python/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

更多推荐

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

本文发布于:2023-06-13 00:04:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/670352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:器中   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!