Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using newly installed modules without restarting an interactive session

Tags:

python

import

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?

like image 753
GJ. Avatar asked Jan 18 '26 18:01

GJ.


1 Answers

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)
like image 85
Torxed Avatar answered Jan 21 '26 07:01

Torxed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!