gpt4 book ai didi

python : "de-import", "re-import", "reset import"?

转载 作者:太空宇宙 更新时间:2023-11-03 11:43:05 29 4
gpt4 key购买 nike

我调试(在 PyCharm 中)一个脚本。我在断点处停止,然后转到调试控制台窗口,然后从那里调用导入行,如下所示:

import my_util1 from my_utils

然后我调用 my_util1。到目前为止,一切正常。然后我改变了“my_util1”中的一些东西。现在我想调用(更新的)my_util1,但我不能:系统(Python?Pycharm?)仅“看到”my_util1 的先前版本。

除了退出 PyCharm 并重新启动项目之外,是否有可能“重置”(刷新)我之前导入的内容或“重新导入”它?

这与动态更改正在调试的实际代码无关。我正在寻找的任务更简单 - 只需撤消“导入”操作,或立即重置/清除/刷新所有“导入”就足够了。此外,该操作可以在调试器窗口中完成,而不是在代码窗口中。

最佳答案

sys.modules可以被操纵以改变 Python 对当前导入内容的看法。引用 Python 文档:

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.

示例用法:

import sys
import my_util1 from my_utils

# Now sys.modules['my_utils'] exists and my_util1 is a local name.

del sys.modules['my_utils']

# my_util1 still exists as a local name, but Python has "forgotten" the import.

import my_util1 from my_utils
# This re-imports my_utils and binds the new my_util1.

关于 python : "de-import", "re-import", "reset import"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301092/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com