Important
This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.
If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).
Module: core.history
History related magics and functionality
6 Classes
- class IPython.core.history.OperationalError
Bases:
DatabaseError
- class IPython.core.history.HistoryAccessorBase(**kwargs: Any)
Bases:
LoggingConfigurable
An abstract class for History Accessors
- class IPython.core.history.HistoryAccessor(**kwargs: Any)
Bases:
HistoryAccessorBase
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: str = 'default', hist_file: str = '', **traits: Any) None
Create a new history accessor.
- connection_options
Options for configuring the SQLite connection
These options are passed as keyword args to sqlite3.connect when establishing database connections.
- enabled
enable the SQLite history
set enabled=False to disable the SQLite history, in which case there will be no stored history, no SQLite connection, and no background saving thread. This may be necessary in some threaded environments where IPython is embedded.
- get_last_session_id() int | None
Get the last session ID currently in the database.
Within IPython, this should be the same as the value stored in
HistoryManager.session_number
.
- get_range(session: int, start: int = 1, stop: int | None = None, raw: bool = True, output: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
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.
- Return type:
entries
- get_range_by_str(rangestr: str, raw: bool = True, output: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
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”. If empty string is used, this will return everything from current session’s history.
See the documentation of
%history()
for the full details.raw (bool) – As
get_range()
output (bool) – As
get_range()
- Return type:
Tuples as
get_range()
- get_session_info(session: int) tuple[int, datetime, datetime | None, int | None, str]
Get info about a session.
- Parameters:
session (int) – Session number to retrieve.
- Returns:
session_id (int) – Session ID number
start (datetime) – Timestamp for the start of the session.
end (datetime) – Timestamp for the end of the session, or None if IPython crashed.
num_cmds (int) – Number of commands run, or None if IPython crashed.
remark (str) – A manually set description.
- get_tail(n: int = 10, raw: bool = True, output: bool = False, include_latest: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
Get the last n lines from the history database.
- Parameters:
n (int) – The number of lines to get
raw (bool) – See
get_range()
output (bool) – See
get_range()
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.
- Return type:
Tuples as
get_range()
- hist_file
Path to file to use for SQLite history database.
By default, IPython will put the history database in the IPython profile directory. If you would rather share one history among profiles, you can set this value in each, so that they are consistent.
Due to an issue with fcntl, SQLite is known to misbehave on some NFS mounts. If you see IPython hanging, try setting this to something on a local disk, e.g:
ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
you can also use the specific value
:memory:
(including the colon at both end but not the back ticks), to avoid creating an history file.
- search(pattern: str = '*', raw: bool = True, search_raw: bool = True, output: bool = False, n: int | None = None, unique: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
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 (bool) – See
get_range()
output (bool) – See
get_range()
n (None or int) – If an integer is given, it defines the limit of returned entries.
unique (bool) – When it is true, return only unique entries.
- Return type:
Tuples as
get_range()
- class IPython.core.history.HistoryManager(**kwargs: Any)
Bases:
HistoryAccessor
A class to organize all history-related functionality in one place.
- __init__(shell: InteractiveShell, config: Configuration | None = None, **traits: Any)
Create a new history manager associated with a shell instance.
- db_cache_size
Write to database every x commands (higher values save disk access & power). Values of 1 or less effectively disable caching.
- db_log_output
no)
- Type:
Should the history database include output? (default
- get_range(session: int = 0, start: int = 1, stop: int | None = None, raw: bool = True, output: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
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.
- Return type:
entries
- get_session_info(session: int = 0) tuple[int, datetime, datetime | None, int | None, str]
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 the previous session.
- Returns:
session_id (int) – Session ID number
start (datetime) – Timestamp for the start of the session.
end (datetime) – Timestamp for the end of the session, or None if IPython crashed.
num_cmds (int) – Number of commands run, or None if IPython crashed.
remark (str) – A manually set description.
- get_tail(n: int = 10, raw: bool = True, output: bool = False, include_latest: bool = False) Iterable[tuple[int, int, str | tuple[str, str | None]]]
Get the last n lines from the history database.
Most recent entry last.
Completion will be reordered so that that the last ones are when possible from current session.
- Parameters:
n (int) – The number of lines to get
raw (bool) – See
get_range()
output (bool) – See
get_range()
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.
- Return type:
Tuples as
get_range()
- new_session(conn: Connection | None = None) None
Get a new session number.
- reset(new_session: bool = True) None
Clear the session history, releasing all object references, and optionally open a new session.
- store_inputs(line_num: int, source: str, source_raw: str | None = None) None
Store source and raw input in history and create input cache variables
_i*
.
- store_output(line_num: int) None
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
- writeout_cache(conn: Connection | None = None) None
Write any entries in the cache to the database.
- class IPython.core.history.HistorySavingThread(history_manager: HistoryManager)
Bases:
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: HistoryManager) None
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is a list or tuple of arguments for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
- run() None
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
4 Functions
- IPython.core.history.only_when_enabled(f, self)
Decorator: return an empty list in the absence of sqlite.
- IPython.core.history.catch_corrupt_db(f, self)
A decorator which wraps HistoryAccessor method calls to catch errors from a corrupt SQLite database, move the old database out of the way, and create a new one.
We avoid clobbering larger databases because this may be triggered due to filesystem issues, not just a corrupt file.
- IPython.core.history.hold(ref: ReferenceType[HistoryManager]) Iterator[ReferenceType[HistoryManager]]
Context manger that hold a reference to a weak ref to make sure it is not GC’d during it’s context.
- IPython.core.history.extract_hist_ranges(ranges_str: str) Iterable[tuple[int, int, int | None]]
Turn a string of history ranges into 3-tuples of (session, start, stop).
Empty string results in a
[(0, 1, None)]
, i.e. “everything from current session”.Examples
>>> list(extract_hist_ranges("~8/5-~7/4 2")) [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]