如何在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文本阅读器读取