我在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()
>>>
- 添加
~/.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)
将
export PYTHONSTARTUP="$HOME/.python_profile"
行添加到~/.bashrc
或~/.bash_profile
行运行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文本阅读器读取