Recovering Command History in Jupyter Notebook?

I have been editing a Jupyter Notebook for the past week, and tried saving it today. While attempting to save it, I got an error, so I refreshed the page and successfully saved it.

However, to my dismay almost all of my command history was lost! I still have access to the variables (the kernel never died), but I don't have access to any of the code.

Is there any way to recover the code? The kernel is still running, but I do not see any checkpoints in my notebook.

3 Answers

You can get the IPython history, which Jupyter Notebook uses as its kernel. In one of the cells run:

%history

This will dump a history (good, bad, and ugly) of every command you have run in the current IPython session. It is probably more than you want, but it is better than losing all your work.

Something similar happened to me where I could not save what I did, refreshed the page, and lost all my commands.

You can get your entire notebook history and redirect the output to any given file by running

%history -g -f filename

In my case, I redirected it to a (.py) file. You can find more documentation here under "%history".

2

If your kernel hasn't restarted you can get your code from globals like _i{1,2,3,...}.

The simplest way to find your code is to run something like

print([k for k, v in globals.items() if 'some unique code snippet' in str(v)])

Say you got something like ['_i2', '_i5', '_i9'], then you can

print(_i9)

and copypaste it to a new cell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest