如何在 python 中获取解释器命令历史记录

How to get interpreter commands history in python

我在 python 解释器中插入了几个命令,想在解释器 shell 中重新输入后查看整个历史记录。 我该怎么做?

例如:

$ 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()

并在重新输入后插入类似 history 的内容并能够在命令下方看到插入内容

$ 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()
>>>
  1. 添加~/.python_profile文件:
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. export PYTHONSTARTUP="$HOME/.python_profile" 行添加到 ~/.bashrc~/.bash_profile

  2. 运行 python shell 并插入 myhistory(n: int)myhistory(s: str)

    • myhistory(n: int) 将显示最后使用的第 n 个命令(或 n 行多行命令)
    • myhistory(s: str) 将显示所有带有 s 子字符串
    • 的命令
>>> myhistory(3)
print('world')
exit()
myhistory(3)
>>> myhistory('print')
print('hello')
print('world')
myhistory('print')
>>>

myhistory(s: str) 将只打印包含 s 的一行,即使原始命令是多行的:

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

PS 也 python 历史存储在 ~/.python_history 文件中,可以通过标准 bash 文本阅读器

读取