Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search inside ipython history

Tags:

python

ipython

ipython's %his command outputs recent commands entered by the user. Is it possible to search within these commands? Something like this:

[c for c in %history if c.startswith('plot')] 

EDIT I am not looking for a way to rerun a command, but to locate it in the history list. Of course, sometimes I will want to rerun a command after locating it, either verbatim or with modifications.

EDIT searching with ctr-r and then typing plot gives the most recent command that starts with "plot". It won't list all the commands that start with it. Neither can you search within the middle or the end of the commands

Solution

Expanding PreludeAndFugue's solution here what I was looking for:

[l for l in  _ih if l.startswith('plot')] 

here, the if condition can be substituted by a regex

like image 252
Boris Gorelik Avatar asked Jul 07 '10 10:07

Boris Gorelik


People also ask

How do I search IPython history?

In particular, running the command 'history -f FILENAME' from the IPython Notebook interface will replace FILENAME even if it already exists without confirmation. treat the arg as a glob pattern to search for in (full) history. This includes the saved history (almost all commands ever written).

Where does IPython Store history?

IPython stores its files—config, command history and extensions—in the directory ~/. ipython/ by default. If set, this environment variable should be the path to a directory, which IPython will use for user data.

How do I save IPython history?

Save an iPython session commands/code to a file. You must use the magic method %save : In [1]: %save? Type: Magic function String Form:<bound method CodeMagics.

What is IPython command?

IPython bridges this gap, and gives you a syntax for executing shell commands directly from within the IPython terminal. The magic happens with the exclamation point: anything appearing after ! on a line will be executed not by the Python kernel, but by the system command-line.


2 Answers

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" 
like image 136
user2141650 Avatar answered Oct 04 '22 12:10

user2141650


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

like image 39
fmark Avatar answered Oct 04 '22 13:10

fmark