0

I inserted couple commands in python interpreter and want to see whole history after re-enter in interpreter shell. How caan I do it?

For example:

$ python
Python 3.7.1 (default, Jul 14 2021, 18:08:28) 
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('hello')
>>> print('world')
>>> exit()

And after re-enter insert something like history and be able to see inserted below commands

$ python
Python 3.7.1 (default, Jul 14 2021, 18:08:28) 
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> {some_history_like_command}
print('hello')
print('world')
exit()
>>>
rzlvmp
  • 7,512
  • 5
  • 16
  • 45
  • 2
    Does this answer your question? [How do you see the entire command history in interactive Python?](https://stackoverflow.com/questions/6558765/how-do-you-see-the-entire-command-history-in-interactive-python) – Arvind Oct 25 '21 at 07:59
  • @Arvind Thanks. I really tried to search same question but didn't find. – rzlvmp Oct 25 '21 at 08:03

1 Answers1

0
  1. Add ~/.python_profile file:
def myhistory(condition=None):
  import readline as r
  if type(condition) == int:
    max_length = r.get_current_history_length()
    if max_length <= condition:
      length = [max_length]
    else:
      length = [(max_length-condition), max_length]
    for cmd in [str(r.get_history_item(i+1)) for i in range(*length)]:
      print(cmd)
  else:
    for cmd in [str(r.get_history_item(i+1)) for i in range(r.get_current_history_length())]:
      if condition is None:
        print(cmd)
      else:
        if condition in cmd:
          print(cmd)
  1. Add export PYTHONSTARTUP="$HOME/.python_profile" line into ~/.bashrc or ~/.bash_profile

  2. Run python shell and insert myhistory(n: int) or myhistory(s: str)

    • myhistory(n: int) will show last used nth commands (or n lines for multiline commands)
    • myhistory(s: str) will show all commands with s substring
>>> myhistory(3)
print('world')
exit()
myhistory(3)
>>> myhistory('print')
print('hello')
print('world')
myhistory('print')
>>>

myhistory(s: str) will print only one line with s inclusion even if original command is multiline:

>>> for i in range(1,2):
...   print(i)
... 
>>> myhistory('print')
  print(i)
myhistory('print')
>>>

PS also python history is stored inside ~/.python_history file and may be read by standard bash text readers

rzlvmp
  • 7,512
  • 5
  • 16
  • 45