Recovering command history in Jupyter Notebook?

20,518

Solution 1

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.

Solution 2

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 https://ipython.readthedocs.io/en/stable/interactive/magics.html under "%history".

Share:
20,518
mgoldwasser
Author by

mgoldwasser

Data scientist / developer

Updated on July 09, 2022

Comments

  • mgoldwasser
    mgoldwasser almost 2 years

    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.

  • vestland
    vestland about 4 years
    I just wanted to chip in that when TonyV says "entire" notebook history, he does mean the entire notebook history. I just did this, and %history -g -f filename produced a file with millions of rows where I could even find the very first few lines of python that I ever wrote. This is awesome, and a this answer needs more upvotes.
  • RGD2
    RGD2 over 2 years
    This is a good solution for if you accidentally deleted a cell with an important def in it, and then saved: You consequently can't find that def later after a kernel restart. But you can still grep that saved history file and pull it out again. 'undo' in jupyter does not undelete input cells...