使用新安装的模块而无需重新启动交互式会话 [英] Using newly installed modules without restarting an interactive session
问题描述
在长时间的交互式会话中(使用ipython)我有时需要使用我尚未安装的模块。
During a long interactive session (using ipython) I sometimes need to use a module which I don't already have installed.
安装新模块后,模块在新的交互式会话中可导入,但在安装之前运行的会话中不可导入。由于我正在使用的内存中的所有变量,我不想重新启动会话...
After installing the new module, that module becomes importable in new interactive sessions, but not in the session that was running before the installation. I wouldn't want to restart the session due to all of the variables in memory that I'm working with...
如何才能获得此类以前运行的会话导入新模块?
How can I get such a previously running session to import the new module?
推荐答案
有两种方法可以手动导入Python中的东西(取决于你的python版本)。
There's two ways of manually importing things in Python (depending on your python version).
# Python2
import os
os.chdir('/path')
handle = __import__('scriptname') #without .py
handle.func()
或者你可以执行:
# Python3.3+
import importlib.machinery
loader = importlib.machinery.SourceFileLoader("namespace", '/path/scriptname.py') #including .py
handle = loader.load_module("namespace")
handle.func()
这在以前版本的Python3中有点不同,没有时间或访问权限现在安装旧版本,但我确实记得点击过尝试时几个问题导入,特别是在早期版本中重新加载模块。
重新加载这些模块以防它们发生变化(只是为了详细说明这个答案):
This works a bit differently in previous version of Python3, Don't have the time or access to install older versions now but I do remember hitting a few issues when trying to import and especially reload modules in earlier versions.
To reload these modules in case they change (just to elaborate this answer):
# Python2
reload(handle)
# Python3
import imp
imp.reload(handle)
这篇关于使用新安装的模块而无需重新启动交互式会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!