During a long interactive session (using ipython) I sometimes need to use a module which I don't already have installed.
在长时间的交互式会话(使用ipython)中,我有时需要使用一个我还没有安装的模块。
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?
如何获得这样一个先前运行的会话来导入新模块?
1 个解决方案
#1
2
There's two ways of manually importing things in Python (depending on your python version).
有两种方法可以在Python中手工导入东西(取决于您的Python版本)。
# Python2
import os
os.chdir('/path')
handle = __import__('scriptname') #without .py
handle.func()
Or you can do:
或者你可以做的:
# Python3.3+
import importlib.machinery
loader = importlib.machinery.SourceFileLoader("namespace", '/path/scriptname.py') #including .py
handle = loader.load_module("namespace")
handle.func()
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):
这在以前的Python3版本中工作得有点不同,现在没有时间或访问安装旧版本,但是我记得在尝试导入时遇到了一些问题,特别是在早期版本中重新加载模块。为了重新加载这些模块,以防它们发生变化(只是为了详细说明这个答案):
# Python2
reload(handle)
# Python3
import imp
imp.reload(handle)
#1
2
There's two ways of manually importing things in Python (depending on your python version).
有两种方法可以在Python中手工导入东西(取决于您的Python版本)。
# Python2
import os
os.chdir('/path')
handle = __import__('scriptname') #without .py
handle.func()
Or you can do:
或者你可以做的:
# Python3.3+
import importlib.machinery
loader = importlib.machinery.SourceFileLoader("namespace", '/path/scriptname.py') #including .py
handle = loader.load_module("namespace")
handle.func()
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):
这在以前的Python3版本中工作得有点不同,现在没有时间或访问安装旧版本,但是我记得在尝试导入时遇到了一些问题,特别是在早期版本中重新加载模块。为了重新加载这些模块,以防它们发生变化(只是为了详细说明这个答案):
# Python2
reload(handle)
# Python3
import imp
imp.reload(handle)