如何取消导入已经导入的python模块? [英] How to unimport a python module which is already imported?

查看:110
本文介绍了如何取消导入已经导入的python模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 NumPy/SciPy 很陌生.但是最近,我开始非常积极地使用它进行数值计算,而不是使用 Matlab.

I'm quite new with NumPy/SciPy. But these days, I've started using it very actively for numerical calculation instead of using Matlab.

对于一些简单的计算,我只是在交互模式下进行,而不是编写脚本.在这种情况下,有什么方法可以取消导入一些已经导入的模块?我写python程序的时候可能不需要unimporting,但是在交互模式下就需要了.

For some simple calculations, I do just in the interactive mode rather than writing a script. In this case, are there any ways to unimport some modules which was already imported? Unimporting might not needed when I write python programs, but in the interactive mode, it is needed.

推荐答案

一旦导入,就无法卸载.Python 将模块的副本保存在缓存中,以便下次导入时不必重新加载和重新初始化.

There's no way to unload something once you've imported it. Python keeps a copy of the module in a cache, so the next time you import it it won't have to reload and reinitialize it again.

如果您只需要失去对它的访问权限,您可以使用 del:

If all you need is to lose access to it, you can use del:

import package
del package

如果您对软件包进行了更改并且想要查看更新,您可以重新加载它.请注意,这在某些情况下不起作用,例如如果导入的包还需要重新加载它所依赖的包.在依赖此之前,您应该阅读相关文档.

If you've made a change to a package and you want to see the updates, you can reload it. Note that this won't work in some cases, for example if the imported package also needs to reload a package it depends on. You should read the relevant documentation before relying on this.

对于 2.7 以下的 Python 版本,reload 是一个内置函数:

For Python versions up to 2.7, reload is a built-in function:

reload(package)

对于 Python 3.0 到 3.3 版本,您可以使用 imp.重新加载:

For Python versions 3.0 to 3.3 you can use imp.reload:

import imp
imp.reload(package)

对于 Python 3.4 及更高版本,您可以使用 importlib.重新加载:

For Python versions 3.4 and up you can use importlib.reload:

import importlib
importlib.reload(package)

这篇关于如何取消导入已经导入的python模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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