A simple function to get a history similar to the Unix / Bash version.
Hope this helps some new people.
def ipyhistory(lastn=None): """ param: lastn Defaults to None ie full history. If specified then returns lastn records from history. Also takes -ve sequence for first n history records. """ import readline assert lastn is None or isinstance(lastn, int), "Only integers are allowed." hlen = readline.get_current_history_length() is_neg = lastn is not None and lastn < 0 if not is_neg: flen = len(str(hlen)) if not lastn else len(str(lastn)) for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]: print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)])) else: flen = len(str(-hlen)) for r in range(1, -lastn + 1): print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))
Snippet: tested with Python3. Let me know if there are any glitches with python2. Samples:
Full History: ipyhistory()
Last 10 History: ipyhistory(10)
First 10 History: ipyhistory(-10)
Hope this helps the guys.
Doogle Sep 30 '18 at 7:23 2018-09-30 07:23
source share