IPython Documentation

Table Of Contents

Previous topic

core.formatters

Next topic

core.hooks

This Page

core.history

Module: core.history

Inheritance diagram for IPython.core.history:

History related magics and functionality

Classes

DummyDB

class IPython.core.history.DummyDB

Bases: object

Dummy DB that will act as a black hole for history.

Only used in the absence of sqlite

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

commit(*args, **kwargs)
execute(*args, **kwargs)

HistoryAccessor

class IPython.core.history.HistoryAccessor(profile='default', hist_file=u'', config=None, **traits)

Bases: IPython.config.configurable.Configurable

Access the history database without adding to it.

This is intended for use by standalone history tools. IPython shells use HistoryManager, below, which is a subclass of this.

__init__(profile='default', hist_file=u'', config=None, **traits)

Create a new history accessor.

Parameters :

profile : str

The name of the profile from which to open history.

hist_file : str

Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile.

config : :

Config object. hist_file can also be set through this.

classmethod class_config_section()

Get the config class config section

classmethod class_get_help(inst=None)

Get the help string for this class in ReST format.

If inst is given, it’s current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait, inst=None)

Get the help string for a single trait.

If inst is given, it’s current trait values will be used in place of the class default.

classmethod class_print_help(inst=None)

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata)

Get a list of all the names of this classes traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata)

Get a list of all the traits of this class.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

config

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

db

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

get_range(session, start=1, stop=None, raw=True, output=False)

Retrieve input by session.

Parameters :

session : int

Session number to retrieve.

start : int

First line to retrieve.

stop : int

End of line range (excluded from output itself). If None, retrieve to the end of the session.

raw : bool

If True, return untranslated input

output : bool

If True, attempt to include output. This will be ‘real’ Python objects for the current session, or text reprs from previous sessions if db_log_output was enabled at the time. Where no output is found, None is used.

Returns :

An iterator over the desired lines. Each line is a 3-tuple, either :

(session, line, input) if output is False, or :

(session, line, (input, output)) if output is True. :

get_range_by_str(rangestr, raw=True, output=False)

Get lines of history from a string of ranges, as used by magic commands %hist, %save, %macro, etc.

Parameters :

rangestr : str

A string specifying ranges, e.g. “5 ~2/1-4”. See magic_history() for full details.

raw, output : bool

Returns :

Tuples as :meth:`get_range` :

get_session_info(session=0)

get info about a session

Parameters :

session : int

Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session.

Returns :

(session_id [int], start [datetime], end [datetime], num_cmds [int], remark [unicode]) :

Sessions that are running or did not exit cleanly will have `end=None` :

and `num_cmds=None`. :

get_tail(n=10, raw=True, output=False, include_latest=False)

Get the last n lines from the history database.

Parameters :

n : int

The number of lines to get

raw, output : bool

include_latest : bool

If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it should not return.

Returns :

Tuples as :meth:`get_range` :

hist_file

A trait for unicode strings.

init_db()

Connect to the database, and create tables if necessary.

on_trait_change(handler, name=None, remove=False)

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

Parameters :

handler : callable

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new) or handler(name, old, new).

name : list, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

remove : bool

If False (the default), then install the handler. If True then unintall it.

search(pattern='*', raw=True, search_raw=True, output=False)

Search the database using unix glob-style matching (wildcards * and ?).

Parameters :

pattern : str

The wildcarded pattern to match when searching

search_raw : bool

If True, search the raw input, otherwise, the parsed input

raw, output : bool

Returns :

Tuples as :meth:`get_range` :

trait_metadata(traitname, key)

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this classes traits.

traits(**metadata)

Get a list of all the traits of this class.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

update_config(config)

Fire the traits events when the config is updated.

writeout_cache()

Overridden by HistoryManager to dump the cache before certain database lookups.

HistoryManager

class IPython.core.history.HistoryManager(shell=None, config=None, **traits)

Bases: IPython.core.history.HistoryAccessor

A class to organize all history-related functionality in one place.

__init__(shell=None, config=None, **traits)

Create a new history manager associated with a shell instance.

classmethod class_config_section()

Get the config class config section

classmethod class_get_help(inst=None)

Get the help string for this class in ReST format.

If inst is given, it’s current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait, inst=None)

Get the help string for a single trait.

If inst is given, it’s current trait values will be used in place of the class default.

classmethod class_print_help(inst=None)

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata)

Get a list of all the names of this classes traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata)

Get a list of all the traits of this class.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

config

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

db

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

db_cache_size

An integer trait.

Longs that are unnecessary (<= sys.maxint) are cast to ints.

db_input_cache

An instance of a Python list.

db_log_output

A boolean (True, False) trait.

db_output_cache

An instance of a Python list.

dir_hist

An instance of a Python list.

end_session()

Close the database session, filling in the end time and line count.

get_range(session=0, start=1, stop=None, raw=True, output=False)

Retrieve input by session.

Parameters :

session : int

Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session.

start : int

First line to retrieve.

stop : int

End of line range (excluded from output itself). If None, retrieve to the end of the session.

raw : bool

If True, return untranslated input

output : bool

If True, attempt to include output. This will be ‘real’ Python objects for the current session, or text reprs from previous sessions if db_log_output was enabled at the time. Where no output is found, None is used.

Returns :

An iterator over the desired lines. Each line is a 3-tuple, either :

(session, line, input) if output is False, or :

(session, line, (input, output)) if output is True. :

get_range_by_str(rangestr, raw=True, output=False)

Get lines of history from a string of ranges, as used by magic commands %hist, %save, %macro, etc.

Parameters :

rangestr : str

A string specifying ranges, e.g. “5 ~2/1-4”. See magic_history() for full details.

raw, output : bool

Returns :

Tuples as :meth:`get_range` :

get_session_info(session=0)

get info about a session

Parameters :

session : int

Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session.

Returns :

(session_id [int], start [datetime], end [datetime], num_cmds [int], remark [unicode]) :

Sessions that are running or did not exit cleanly will have `end=None` :

and `num_cmds=None`. :

get_tail(n=10, raw=True, output=False, include_latest=False)

Get the last n lines from the history database.

Parameters :

n : int

The number of lines to get

raw, output : bool

include_latest : bool

If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it should not return.

Returns :

Tuples as :meth:`get_range` :

hist_file

A trait for unicode strings.

init_db()

Connect to the database, and create tables if necessary.

input_hist_parsed

An instance of a Python list.

input_hist_raw

An instance of a Python list.

name_session(name)

Give the current session a name in the history database.

new_session(conn=None)

Get a new session number.

on_trait_change(handler, name=None, remove=False)

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

Parameters :

handler : callable

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new) or handler(name, old, new).

name : list, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

remove : bool

If False (the default), then install the handler. If True then unintall it.

output_hist

An instance of a Python dict.

output_hist_reprs

An instance of a Python dict.

reset(new_session=True)

Clear the session history, releasing all object references, and optionally open a new session.

save_flag

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

save_thread

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

search(pattern='*', raw=True, search_raw=True, output=False)

Search the database using unix glob-style matching (wildcards * and ?).

Parameters :

pattern : str

The wildcarded pattern to match when searching

search_raw : bool

If True, search the raw input, otherwise, the parsed input

raw, output : bool

Returns :

Tuples as :meth:`get_range` :

session_number

An integer trait.

Longs that are unnecessary (<= sys.maxint) are cast to ints.

shell

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

store_inputs(line_num, source, source_raw=None)

Store source and raw input in history and create input cache variables _i*.

Parameters :

line_num : int

The prompt number of this input.

source : str

Python input.

source_raw : str, optional

If given, this is the raw input without any IPython transformations applied to it. If not given, source is used.

store_output(line_num)

If database output logging is enabled, this saves all the outputs from the indicated prompt number to the database. It’s called by run_cell after code has been executed.

Parameters :

line_num : int

The line number from which to save outputs

trait_metadata(traitname, key)

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this classes traits.

traits(**metadata)

Get a list of all the traits of this class.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

update_config(config)

Fire the traits events when the config is updated.

writeout_cache(conn=None)

Write any entries in the cache to the database.

HistorySavingThread

class IPython.core.history.HistorySavingThread(history_manager)

Bases: threading.Thread

This thread takes care of writing history to the database, so that the UI isn’t held up while that happens.

It waits for the HistoryManager’s save_flag to be set, then writes out the history cache. The main thread is responsible for setting the flag when the cache size reaches a defined threshold.

__init__(history_manager)
getName()
ident
isAlive()
isDaemon()
is_alive()
join(timeout=None)
name
run()
setDaemon(daemonic)
setName(name)
start()
stop()

This can be called from the main thread to safely stop this thread.

Note that it does not attempt to write out remaining history before exiting. That should be done by calling the HistoryManager’s end_session method.

Functions

IPython.core.history.extract_hist_ranges(ranges_str)

Turn a string of history ranges into 3-tuples of (session, start, stop).

Examples

list(extract_input_ranges(“~8/5-~7/4 2”)) [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]

IPython.core.history.init_ipython(ip)
IPython.core.history.magic_history(self, parameter_s='')

Print input history (_i<n> variables), with most recent last.

%history -> print at most 40 inputs (some may be multi-line)%history n -> print at most n inputs%history n1 n2 -> print inputs between n1 and n2 (n2 not included)

By default, input history is printed without line numbers so it can be directly pasted into an editor. Use -n to show them.

Ranges of history can be indicated using the syntax: 4 : Line 4, current session 4-6 : Lines 4-6, current session 243/1-5: Lines 1-5, session 243 ~2/7 : Line 7, session 2 before current ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line

of 6 sessions ago.

Multiple ranges can be entered, separated by spaces

The same syntax is used by %macro, %save, %edit, %rerun

Options:

-n: print line numbers for each input. This feature is only available if numbered prompts are in use.

-o: also print outputs for each input.

-p: print classic ‘>>>’ python prompts before each input. This is useful
for making documentation, and in conjunction with -o, for producing doctest-ready output.

-r: (default) print the ‘raw’ history, i.e. the actual commands you typed.

-t: print the ‘translated’ history, as IPython understands it. IPython filters your input and converts it all into valid Python source before executing it (things like magics or aliases are turned into function calls, for example). With this option, you’ll see the native history instead of the user-entered version: ‘%cd /’ will be seen as ‘get_ipython().magic(“%cd /”)’ instead of ‘%cd /’.

-g: treat the arg as a pattern to grep for in (full) history. This includes the saved history (almost all commands ever written). Use ‘%hist -g’ to show full saved history (may be very long).

-l: get the last n lines from all sessions. Specify n as a single arg, or the default is the last 10 lines.

-f FILENAME: instead of printing the output to the screen, redirect it to
the given file. The file is always overwritten, though when it can, IPython asks for confirmation first. In particular, running the command “history -f FILENAME” from the IPython Notebook interface will replace FILENAME even if it already exists without confirmation.

Examples

In [6]: %hist -n 4 6
4:a = 12
5:print a**2
IPython.core.history.magic_rep(self, arg)

Repeat a command, or get command to input line for editing.

%recall and %rep are equivalent.

  • %recall (no arguments):

Place a string version of last computation result (stored in the special ‘_’ variable) to the next input prompt. Allows you to create elaborate command lines without using copy-paste:

 In[1]: l = ["hei", "vaan"]
 In[2]: "".join(l)
Out[2]: heivaan
 In[3]: %rep
 In[4]: heivaan_ <== cursor blinking

%recall 45

Place history line 45 on the next input prompt. Use %hist to find out the number.

%recall 1-4

Combine the specified lines into one cell, and place it on the next input prompt. See %history for the slice syntax.

%recall foo+bar

If foo+bar can be evaluated in the user namespace, the result is placed at the next input prompt. Otherwise, the history is searched for lines which contain that substring, and the most recent one is placed at the next input prompt.

IPython.core.history.magic_rerun(self, parameter_s='')

Re-run previous input

By default, you can specify ranges of input history to be repeated (as with %history). With no arguments, it will repeat the last line.

Options:

-l <n> : Repeat the last n lines of input, not including the current command.

-g foo : Repeat the most recent line which contains foo

IPython.core.history.needs_sqlite(f)

return an empty list in the absence of sqlite