Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在交互式Python中查看整个命令历史记录?_Python_Macos - Fatal编程技术网

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

如何在交互式Python中查看整个命令历史记录?,python,macos,Python,Macos,我正在Mac OS X上使用默认的python解释器,并且我使用了Cmd+K(清除)我以前的命令。我可以用箭头键逐一浏览。但是bash shell中是否有一个类似于--history选项的选项,可以显示到目前为止输入的所有命令?用于获取长度并查看每个命令。用于打印整个历史记录的代码: 一行(快速复制和粘贴): (或更长版本…) 一行(快速复制和粘贴): (或更长版本…) 注意:get\u history\u item()从1到n进行索引。使用python 3解释器将历史记录写入 ~/.pytho

我正在Mac OS X上使用默认的python解释器,并且我使用了Cmd+K(清除)我以前的命令。我可以用箭头键逐一浏览。但是bash shell中是否有一个类似于--history选项的选项,可以显示到目前为止输入的所有命令?

用于获取长度并查看每个命令。

用于打印整个历史记录的代码:

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

(或更长版本…)

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

(或更长版本…)


注意
get\u history\u item()
从1到n进行索引。

使用python 3解释器将历史记录写入

~/.python\u历史记录

,因为上述内容仅适用于Python2.x Python3.x(特别是3.5)与之类似,但稍作修改:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))
注意额外的()


(使用shell脚本解析.python_历史或使用python修改上述代码取决于个人喜好和情况,imho)

这将为您提供以单独的行打印的命令:

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

@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 

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

import readline
readline.write_history_file('python_history.txt')
帮助功能提供:

module readline中内置函数write_history_文件的帮助:
写入历史文件(…)
写入历史文件([filename])->无
保存一个读线历史文件。
默认文件名为~/.history。

一个简单的函数,用于获取与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)]))
def ipyhistory(lastn=None):
"""
参数:lastn默认为无,即完整历史记录。如果指定,则从历史记录返回lastn记录。
对于前n个历史记录,也采用-ve序列。
"""
导入读线
assert lastn为None或isinstance(lastn,int),“只允许整数。”
hlen=readline.get\u current\u history\u length()
is_neg=lastn不是无且lastn<0
如果不是_neg:
flen=len(str(hlen))如果不是lastn,则为len(str(lastn))
对于范围(1,hlen+1)中的r,如果不是lastn else范围(1,hlen+1)[-lastn:]:
打印(“:”.join([str(r如果不是lastn,则为r+lastn-hlen).rjust(flen),readline.get_history_item(r)])
其他:
flen=len(str(-hlen))
对于范围(1,-lastn+1)内的r:
打印(“:”.join([str(r).rjust(flen),readline.get_history_item(r)])
代码片段:使用Python3进行测试。如果python2有任何问题,请告诉我。 样本:

完整历史记录:
ipyhistory()

最后10个历史记录:
ipy历史记录(10)

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


希望它能帮助大家。

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

重新显示of的答案,该答案不打印行号,但允许指定要打印的行号

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))
def历史记录(lastn=None):
"""
参数:lastn默认为无,即完整历史记录。如果指定,则从历史记录返回lastn记录。
对于前n个历史记录,也采用-ve序列。
"""
导入读线
assert lastn为None或isinstance(lastn,int),“只允许整数。”
hlen=readline.get\u current\u history\u length()
is_neg=lastn不是无且lastn<0
如果不是_neg:
对于范围(1,hlen+1)中的r,如果不是lastn else范围(1,hlen+1)[-lastn:]:
打印(读取行。获取历史记录项目(r))
其他:
对于范围(1,-lastn+1)内的r:
打印(读取行。获取历史记录项目(r))

historyshell命令是一个与其他命令类似的程序。它不是
bash
命令中的“选项”。确切地说:
history
是一个内置的shell。因为答案是
%history
。而
-g
选项得到。%history-g+%edit-works-best只需问一行:
importreadline;打印“\n”.join([str(readline.get_history_item(i))代表范围内的i(readline.get_current_history_length())))
这个答案(及其非示例对应项)举例说明了示例对人们的重要性。谢谢,酷!我在Python解释器启动脚本(env.var
$PYTHONSTARTUP
指向的脚本)中添加了一个带有上述内容的
history()
函数。从现在起,我只需在任何解释器会话中键入
history()
;-)每次我忘记这是怎么做到的,我都会来这里寻找答案,谢谢你,丹尼斯。我主演了这部电影,谁知道是什么时候,我又回来了。我没有这个目录,我使用的是Python 3.5.2,这将适用于类似Unix的操作系统。我可以通过
cat~/,在macOS上检索我的历史记录。python_history
感谢您的回答。后来,我在这里的文档中发现了这一点:不幸的是,在使用虚拟环境时,历史记录似乎没有得到更新:-/您需要
退出()
解释器,以便将当前会话历史记录包含在
~/.python_history
中。您能否更具体地格式化代码?你是说括号不匹配吗?我用一些简单的缩进修正了格式@AleksAndreev你可以取消你的否决票。嗨,谢谢。我将您的代码片段制作成xx.py文件。然后在打开python之后,我导入了xx。然后我尝试了ipyhistory(),但它说,“>>>ipyhistory回溯(最后一次调用):文件“”,第1行,在NameError中:未定义名称“ipyhistory”。出什么事了?我一直以来都是这样,但我喜欢线条限制功能。(即使在Unix上,我通常
cut-c8
out)这种情况会在python会话中像ruby的pry history一样持续存在吗?也许这个答案是在readline函数之前写的,但是为什么不使用readline.write_history_文件呢@lacostenycoder你呢
#!/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 
import readline
readline.write_history_file('python_history.txt')
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)]))
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))