Last active
August 22, 2023 10:00
-
-
Save wolkenarchitekt/4037761 to your computer and use it in GitHub Desktop.
Access complete IPython history
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Extract a session from the IPython input history. | |
""" | |
import sys | |
import codecs | |
from IPython.core.history import HistoryAccessor | |
class MyHistoryAccessor(HistoryAccessor): | |
""" Modified HistoryAccessor to fetch the whole ipython history across all sessions """ | |
def get_tail(self, 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 | |
See :meth:`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. | |
Returns | |
------- | |
Tuples as :meth:`get_range` | |
""" | |
self.writeout_cache() | |
if not include_latest: | |
n += 1 | |
if n == None: | |
cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", | |
(n,), raw=raw, output=output) | |
else: | |
cur = self._run_sql("ORDER BY session DESC, line DESC", | |
(), raw=raw, output=output) | |
if not include_latest: | |
return reversed(list(cur)[1:]) | |
return reversed(list(cur)) | |
# OrderedSet would be nicer, but for simplicity we use this approach | |
def rem_dups(lst): | |
from itertools import groupby | |
return [ key for key,_ in groupby(lst)] | |
if __name__ == '__main__': | |
# Syntax: ipythonhist [LAST X ITEMS] | |
hist = MyHistoryAccessor() | |
history = list(hist.get_tail()) | |
history = rem_dups(history) | |
if len(sys.argv) > 1: | |
head = int(sys.argv[1]) | |
for entry in history[-head:]: | |
print entry[2] | |
else: | |
for entry in history: | |
print entry[2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment