简体   繁体   中英

How to refresh a Python import in a Jupyter Notebook cell?

I have two files:

MyModule.py MyNotebook.ipynb

I am using Jupyter Notebook, latest, and Python, latest. I have two code cells in my Notebook.

Cell #1

import some stuff
Run some code
(Keep everything in the environment takes about five minutes to run this cell).

Cell #2

import MyModule
Execute code from MyModule

I would like to make code changes in MyModule.py and rerun Cell #2 but without restarting the kernel ( Cell #1 did a fair amount of work which I don't want to rerun each time). If I simply run the second cell, those changes made to MyModule.py do not propagate through. I did some digging, and I tried using importlib.reload. The actual code for Cell #2 :

from Nash.IOEngineNash import *
import importlib
importlib.reload(Nash.IOEngineNash)

Unfortunately, this isn't quite working. How can I push those changes in MyModule.py (or Nash/IOEngineNash.py in actual fact) into my Notebook without restarting the kernel and running from scratch?

I faced a similar issue, while importing a custom script in jupyter notebook

Try importing the module as an alias then reloading it


import Nash as nash
from importlib import reload
reload(nash)

To make sure that all references to the old version of the module are updated, you might want to re-import it after reloading, eg

import mymodule
reload(mymodule)
import mymodule

Issues may arise due to implicit dependencies, because importlib.reload only reloads the (top-level) module that you ask it to reload, not its submodules or external modules.

If you want to reload a module recursively, you might have a look at this gist , which allows you to simply add a line like this at the top of a notebook cell:

%reload mymodule
import mymodule

This recursively reloads the mymodule and all of its submodules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM