def _find_df_in_history(shell): dfs = shell.run_line_magic("who_ls", "DataFrame") history = HistoryAccessor() commands = [ command for _, _, command in history.get_tail(include_latest=True) ] return _match_df_name(dfs, commands)
def _parse_database(sqlite_database: str) -> Results: hist = HistoryAccessor(hist_file=sqlite_database) total_sessions = hist.get_last_session_id() for sess in range(1, total_sessions): # get when this session started, use that as timestamp session_info = hist.get_session_info(sess) assert len(session_info) == 5 # sanity checks start_time = session_info[1] assert isinstance(start_time, datetime) for msg in hist.get_range(sess).fetchall(): # sqlite cursor assert len(msg) == 3 assert isinstance(msg[-1], str) yield Command(command=msg[-1], dt=start_time)
def get_last_n_commands(n): """ Find the last n commands entered in the IPython session Parameters ---------- n : int Number of commands to retrieve Returns ------- commands : str Block of text representing user input """ # Ignore warnings generated by the HistoryAccessor. This can be removed # when https://github.com/ipython/ipython/pull/11054 reaches our release # environment with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) ha = HistoryAccessor() # Parse the last n commands of the IPython history, joining printed # messages return '\n'.join([cmd[2] for cmd in ha.get_tail(n, include_latest=True)])
Example: ./ipython-get-history.py 57 record.ipy This script is a simple demonstration of HistoryAccessor. It should be possible to build much more flexible and powerful tools to browse and pull from the history database. """ import sys from IPython.core.history import HistoryAccessor session_number = int(sys.argv[1]) if len(sys.argv) > 2: dest = open(sys.argv[2], "w") raw = not sys.argv[2].endswith('.py') else: dest = sys.stdout raw = True with dest: dest.write("# coding: utf-8\n") # Profiles other than 'default' can be specified here with a profile= argument: hist = HistoryAccessor() for session, lineno, cell in hist.get_range(session=session_number, raw=raw): cell = cell.encode('utf-8') # This line is only needed on Python 2. dest.write(cell + '\n')
special syntax) will be extracted. Example: ./ipython-get-history.py 57 record.ipy This script is a simple demonstration of HistoryAccessor. It should be possible to build much more flexible and powerful tools to browse and pull from the history database. """ import sys import codecs from IPython.core.history import HistoryAccessor session_number = int(sys.argv[1]) if len(sys.argv) > 2: dest = open(sys.argv[2], "w") raw = not sys.argv[2].endswith('.py') else: dest = sys.stdout raw = True dest.write("# coding: utf-8\n") # Profiles other than 'default' can be specified here with a profile= argument: hist = HistoryAccessor() for session, lineno, cell in hist.get_range(session=session_number, raw=raw): # To use this in Python 3, remove the .encode() here: dest.write(cell.encode('utf-8') + '\n')