我正在Mac OS X上的默认python解释器上工作,我Cmd+K(清除)我之前的命令。我可以用方向键逐个浏览它们。但是bash shell中是否存在类似——history选项的选项,可以显示到目前为止输入的所有命令?


当前回答

在IPython中,%history -g应该提供整个命令历史。

默认配置还将历史记录保存到用户目录中名为.python_history的文件中。

其他回答

在IPython中,%history -g应该提供整个命令历史。

默认配置还将历史记录保存到用户目录中名为.python_history的文件中。

这应该会让你在单独的行中打印出命令:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

因为上面只适用于python 2.x 对于python 3。X(特别是3.5)类似,但略有修改:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

注意额外的()

(使用shell脚本解析.python_history或使用python修改上面的代码是个人喜好和情况的问题)

使用readline.get_current_history_length()获取长度,并使用readline.get_history_item()查看每个长度。

打印整个历史的代码:

Python 3

一行代码(快速复制和粘贴):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(或者更长的版本…)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

一行代码(快速复制和粘贴):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(或者更长的版本…)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

注意:get_history_item()的索引从1到n。