繁体   English   中英

您如何查看交互式 Python 中的整个命令历史记录?

[英]How do you see the entire command history in interactive Python?

我正在使用 Mac OS X 上的默认 python 解释器,我使用 Cmd + K (清除)我之前的命令。 我可以使用箭头键一一通过它们 go。 但是在 bash shell 中是否有类似 --history 选项的选项,它显示了您迄今为止输入的所有命令?

打印整个历史的代码:

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。

使用 python 3 解释器将历史写入
~/.python_history

如果要将历史记录写入文件:

import readline
readline.write_history_file('python_history.txt')

帮助 function 给出:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

在 IPython 中%history -g应该给你整个命令历史。 默认配置还将您的历史记录保存到用户目录中名为.python_history 的文件中。

由于上述仅适用于 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 修改上述代码是个人喜好和情况恕我直言)

@Jason-V,真的很有帮助,谢谢。 然后,我找到了这个例子并组成了自己的片段。

#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
  readline.read_history_file(python_history)
  readline.parse_and_bind("tab: complete")
  readline.set_history_length(5000)
  atexit.register(readline.write_history_file, python_history)
except IOError:
  pass
del os, python_history, readline, atexit 

一个简单的 function 获取类似于 unix/bash 版本的历史记录。

希望它可以帮助一些新人。

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

片段:使用 Python3 测试。 让我知道python2是否有任何故障。 样品:

完整历史: ipyhistory()

最近 10 个历史记录: ipyhistory(10)

前 10 个历史记录: ipyhistory(-10)

希望对小伙伴有所帮助。

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

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

Doogle的答案的重新散列不打印行号,但允许指定要打印的行数。

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM