Search inside ipython history

If you want to re-run a command in your history, try Ctrl-r and then your search string.


Even better: %hist -g pattern greps your past history for pattern. You can additionally restrict your search to the current session, or to a particular range of lines. See %hist?

So for @BorisGorelik's question you would have to do

%hist -g plot

Unfortunately you cannot do

%hist -g ^plot

nor

%hist -g "^plot"

Similar to the first answer you can do the following:

''.join(_ih).split('\n')

However, when iterating through the command history items you can do the following. Thus you can create your list comprehension from this.

for item in _ih:
    print item

This is documented in the following section of the documentation: http://ipython.org/ipython-doc/dev/interactive/reference.html#input-caching-system


I usually find myself wanting to search the entire ipython history across all previous and current sessions. For this I use:

from IPython.core.history import HistoryAccessor
hista = HistoryAccessor()
z1 = hista.search('*numpy*corr*')
z1.fetchall()

OR (don't run both or you will corrupt/erase your history)

ip = get_ipython()
sqlite_cursor = ip.history_manager.search('*numpy*corr*')
sqlite_cursor.fetchall()

The search string is not a regular expression. The iPython history_manager uses sqlite's glob * search syntax instead.

Tags:

Python

Ipython