Using newly installed modules without restarting an interactive session
Asked Answered
L

2

16

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?

Leitman answered 26/5, 2014 at 8:26 Comment(0)
C
5

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()

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):

# Python2
reload(handle)


# Python3
import imp
imp.reload(handle)
Cray answered 26/5, 2014 at 8:30 Comment(3)
what should scriptname be? the directory in question has an __init__.py as well as a bunch of other .py and .pyc files...Greeneyed
@Greeneyed "scriptname.py" and then do the code above handle = __import__('scriptname') #without .py OR you do the second option.Cray
namespace is the full module name. Something like mymath.trig: SourceFileLoader("mymath.trig", '/home/idbrii/py/package/mymath/trig.py')Triglyceride
T
0

Here's a slightly simpler answer for top-level modules in python3:

# import it to use it
import modulename

# reimport it with importlib
import importlib
print(importlib.reload(__import__("modulename")))

Worked for me on python 3.9. I think it only reimports the top-level module, so you'd want the SourceFileLoader solution for child modules.

Triglyceride answered 27/11, 2020 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.