Using new modules without restarting the interactive session

During a long interactive session (using ipython), I sometimes need to use a module that I have not yet installed.

After installing a new module, this module becomes imported in new interactive sessions, but not in a session that was started before installation. I would not want to restart the session because of all the variables in memory that I work with ...

How can I get such a previously launched session to import a new module?

+7
python import
source share
1 answer

There are two ways to import manually in Python (depending on your version of 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() 

In the previous version of Python3, this is a bit different, now you do not have time or access to install older versions, but I remember that I had several problems when trying to import and especially reload the modules in earlier versions.


To reload these modules if they change (just to develop this answer):

 # Python2 reload(handle) 


 # Python3 import imp imp.reload(handle) 
+2
source share

All Articles