简体   繁体   English

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

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

I'm working on the default python interpreter on Mac OS X, and I Cmd + K (cleared) my earlier commands.我正在使用 Mac OS X 上的默认 python 解释器,我使用 Cmd + K (清除)我之前的命令。 I can go through them one by one using the arrow keys.我可以使用箭头键一一通过它们 go。 But is there an option like the --history option in bash shell, which shows you all the commands you've entered so far?但是在 bash shell 中是否有类似 --history 选项的选项,它显示了您迄今为止输入的所有命令?

Code for printing the entire history:打印整个历史的代码:

Python 3 Python 3

One-liner (quick copy and paste):单行(快速复制和粘贴):

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

(Or longer version...) (或更长的版本...)

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

Python 2 Python 2

One-liner (quick copy and paste):单行(快速复制和粘贴):

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

(Or longer version...) (或更长的版本...)

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

Note : get_history_item() is indexed from 1 to n.注意get_history_item()的索引从 1 到 n。

With python 3 interpreter the history is written to使用 python 3 解释器将历史写入
~/.python_history

If you want to write the history to a file:如果要将历史记录写入文件:

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

The help function gives:帮助 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.

In IPython %history -g should give you the entire command history.在 IPython 中%history -g应该给你整个命令历史。 The default configuration also saves your history into a file named.python_history in your user directory.默认配置还将您的历史记录保存到用户目录中名为.python_history 的文件中。

Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:由于上述仅适用于 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))

note the extra ()注意额外的 ()

(using shell scripts to parse.python_history or using python to modify the above code is a matter of personal taste and situation imho) (使用 shell 脚本解析.python_history 或使用 python 修改上述代码是个人喜好和情况恕我直言)

@Jason-V, it really help, thanks. @Jason-V,真的很有帮助,谢谢。 then, i found this examples and composed to own snippet.然后,我找到了这个例子并组成了自己的片段。

#!/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 

A simple function to get the history similar to unix/bash version.一个简单的 function 获取类似于 unix/bash 版本的历史记录。

Hope it helps some new folks.希望它可以帮助一些新人。

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)]))

Snippet: Tested with Python3.片段:使用 Python3 测试。 Let me know if there are any glitches with python2.让我知道python2是否有任何故障。 Samples:样品:

Full History: ipyhistory()完整历史: ipyhistory()

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

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

Hope it helps fellas.希望对小伙伴有所帮助。

This should give you the commands printed out in separate lines:这应该会给你在单独的行中打印出来的命令:

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

Rehash of Doogle 's answer that doesn't printline numbers, but does allow specifying the number of lines to print. 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