Skillversitas

The history Command

IPython keeps a complete history of every input and output you have ever run, searchable from the command line and from within cells. The history system is one of the most underused productivity features in the notebook workflow.

Viewing History

%history
%history -g "requests.get"     # search across all sessions

Recent Entries

%history -20        # last 20 inputs
%history -o -10     # last 10 outputs too
%history -p -g "df.to_csv"   # show matching lines
%history -l 100-150           # a range of line numbers

Recalling Commands

At the prompt, Esc + double-quote jumps to the last double-quoted string (great for URLs); Up-arrow is the basic recaller. Programmatically, history() returns the session's inputs:

print(history(6, 8))  # inputs 6 through 8
print(get_ipython().history_manager.find_hist("to_csv"))

Saving History

%save my_snippets 4-9     # save inputs 4-9 to my_snippets.py
%history -f full_history.py -n  # dump all history, numbered

Practical Uses

  • Find the exact command that produced a chart you liked three weeks ago.
  • Recover a cell after an accidental kernel restart: %history -g "the unique string".
  • Export a session's work to a .py file before converting to a script.

Summary

IPython's history is persistent and searchable: %history -g "pattern" finds any command from any session, %history -N shows recent entries, and %save extracts ranges to files. Learn the search flags and you will never lose a working snippet again.