Module:core.history
History related magics and functionality
7 Classes
- classIPython.core.history.OperationalError
Bases:
DatabaseError
- classIPython.core.history.HistoryAccessorBase(**kwargs:Any)
Bases:
LoggingConfigurableAn abstract class for History Accessors
- classIPython.core.history.HistoryAccessor(**kwargs:Any)
Bases:
HistoryAccessorBaseAccess the history database without adding to it.
This is intended for use by standalone history tools. IPython shells useHistoryManager, below, which is a subclass of this.
- connection_options
Options for configuring the SQLite connection
These options are passed as keyword args to sqlite3.connectwhen 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 somethreaded 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, retrieveto the end of the session.
raw (bool) – If True, return untranslated input
output (bool) – If True, attempt to include output. This will be ‘real’ Pythonobjects for the current session, or text reprs from previoussessions if db_log_output was enabled at the time. Where no outputis 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 magiccommands %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 oneis discarded. This is intended to be used where the functionis 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 IPythonprofile directory. If you would rather share one history amongprofiles, 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 NFSmounts. If you see IPython hanging, try setting this to something on alocal disk, e.g:
ipython--HistoryManager.hist_file=/tmp/ipython_hist.sqlite
you can also use the specific value
:memory:(including the colonat 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 orint) – If an integer is given, it defines the limit ofreturned entries.
unique (bool) – When it is true, return only unique entries.
- Return type:
Tuples as
get_range()
- classIPython.core.history.HistoryOutput(output_type:"typing.Literal['out_stream','err_stream','display_data','execute_result']",bundle:'typing.Dict[str,str|list[str]]')
Bases:
object
- classIPython.core.history.HistoryManager(**kwargs:Any)
Bases:
HistoryAccessorA 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 negativenumbers 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, retrieveto the end of the session.
raw (bool) – If True, return untranslated input
output (bool) – If True, attempt to include output. This will be ‘real’ Pythonobjects for the current session, or text reprs from previoussessions if db_log_output was enabled at the time. Where no outputis 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 negativenumbers 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 whenpossible 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 oneis discarded. This is intended to be used where the functionis 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, andoptionally 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 cachevariables
_i*.
- store_output(line_num:int)→None
If database output logging is enabled, this saves all theoutputs from the indicated prompt number to the database. It’scalled 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.
- classIPython.core.history.HistorySavingThread(history_manager:HistoryManager)
Bases:
ThreadThis thread takes care of writing history to the database, so thatthe UI isn’t held up while that happens.
It waits for the HistoryManager’s save_flag to be set, then writes outthe history cache. The main thread is responsible for setting the flag whenthe 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 ThreadGroupclass 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 ofthe 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 targetinvocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invokethe base class constructor (Thread.__init__()) before doing anythingelse to the thread.
- run()→None
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() methodinvokes the callable object passed to the object’s constructor as thetarget argument, if any, with sequential and keyword arguments takenfrom 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 froma corrupt SQLite database, move the old database out of the way, and createa 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 itis 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 currentsession”.Examples
>>>list(extract_hist_ranges("~8/5-~7/4 2"))[(-8, 5, None), (-7, 1, 5), (0, 2, 3)]>>>list(extract_hist_ranges("~4/"))[(-4, 1, None)]>>>list(extract_hist_ranges("4-"))[(0, 4, None)]>>>list(extract_hist_ranges("~4/4-"))[(-4, 4, None)]