Python:"de-import","re-import","reset import"? [英] Python: "de-import", "re-import", "reset import"?

查看:147
本文介绍了Python:"de-import","re-import","reset import"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I debug (in PyCharm) a script. I stop at a breakpoint, then I go to the debug console window and from there, I invoke an import line, like this:

import my_util1 from my_utils

然后我将其称为my_util1.到目前为止,一切正常.然后,我在"my_util1"中进行更改.现在,我想调用(更新的)my_util1,但是我不能:系统(Python?Pycharm?)仅看到"my_util1"的先前版本.

Then I call my_util1. So far, everything is OK. Then I change something in "my_util1". Now I would like to call the (updated) my_util1 but I cannot: the system (Python? Pycharm?) "sees" only the previous version of my_util1.

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

Is there a possibility to "reset" (refresh) what I imported earlier, or to "re-import" it, other than exiting PyCharm and restarting the project?

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

It is not about dynamically changing the actual code that is being debugged. The task that I am looking for is simpler - it would suffice just to undo an 'import' operation, or to reset/clear/refresh all 'imports' at once. Additionally, the action could be done within the debugger window, not in the code window.

推荐答案

sys.modules 来改变Python关于当前导入内容的想法.引用Python文档:

sys.modules can be manipulated to change Python's ideas of what's currently imported. To quote the Python docs:

这是一个字典,将模块名称映射到已加载的模块.可以对其进行操作以强制重新加载模块和其他技巧.但是,替换字典不一定能按预期工作,并且从字典中删除必要项目可能会导致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"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆