【问题标题】:How to get interpreter commands history in python [duplicate]如何在python中获取解释器命令历史记录[重复]
【发布时间】:2021-10-25 07:54:51
【问题描述】:

我在 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 shell interpreter


【解决方案1】:
  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) 将显示最后使用的 nth 命令(或 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 文本阅读器读取

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 2022-01-20
    • 2010-10-14
    • 2018-06-30
    • 2018-05-10
    • 2013-05-12
    • 2017-06-19
    • 1970-01-01
    • 2011-03-03
    相关资源
    最近更新 更多