36

在对 IPython文档和一些代码进行了一些搜索和搜索之后,我似乎无法弄清楚是否可以将命令历史记录(而不是输出日志)存储到文本文件而不是 SQLite 数据库中。ipython --help-all似乎表明此选项不存在。

这对于.bash_history等常用命令的版本控制非常有用。

编辑:基于@minrk 答案的工作解决方案。

4

5 回答 5

83

您可以使用%history魔术将 IPython 中的所有历史记录导出到文本文件,如下所示:

%history -g -f filename

获得所需内容的一种方法可能是在git hook中进行导出。我通常将这些“同步外部资源”操作放在结帐后的 git 挂钩中。

于 2016-09-09T13:53:11.380 回答
10

您还可以选择要保存的行。例如

%history 1 7-8 10 -f /tmp/bar.py

这会将第 1、7 到 8 行和第 10 行保存到临时文件 bar.py。如果您需要整体,请跳过该行的一部分。

%history -f /tmp/foo.py
于 2019-06-23T17:30:05.267 回答
8

您可以通过在您的启动脚本之一中添加它来模拟 bash 的行为(例如$(ipython locate profile)/startup/log_history.py

import atexit
import os

ip = get_ipython()
LIMIT = 1000 # limit the size of the history

def save_history():
    """save the IPython history to a plaintext file"""
    histfile = os.path.join(ip.profile_dir.location, "history.txt")
    print("Saving plaintext history to %s" % histfile)
    lines = []
    # get previous lines
    # this is only necessary because we truncate the history,
    # otherwise we chould just open with mode='a'
    if os.path.exists(histfile):
        with open(histfile, 'r') as f:
            lines = f.readlines()

    # add any new lines from this session
    lines.extend(record[2] + '\n' for record in ip.history_manager.get_range())

    with open(histfile, 'w') as f:
        # limit to LIMIT entries
        f.writelines(lines[-LIMIT:])

# do the save at exit
atexit.register(save_history)

请注意,这模拟了 bash/readline 历史行为,因为它将在解释器崩溃等时失败。

在一个要点

更新:替代

如果您真正想要的只是有一些可用于 readline 的手动收藏命令(完成、^R 搜索等),您可以进行版本控制,这个启动文件将允许您自己维护该文件,这将纯粹是在除了 IPython 的实际命令历史之外:

import os

ip = get_ipython()

favfile = "readline_favorites"

def load_readline_favorites():
    """load profile_dir/readline_favorites into the readline history"""
    path = os.path.join(ip.profile_dir.location, favfile)
    if not os.path.exists(path):
        return

    with open(path) as f:
        for line in f:
            ip.readline.add_history(line.rstrip('\n'))

if ip.has_readline:
    load_readline_favorites()

把它放到你的profile_default/startup/目录中,然后编辑profile_default/readline_favorites,或者任何你喜欢保留该文件的地方,它会在每个 IPython 会话中显示在 readline 完成等中。

于 2013-05-31T18:14:41.437 回答
7

要保存 Ipython 会话历史记录:

%save [filename] [line start - line end] 

例如:

%save ~/Desktop/Ipython_session.txt 1-31

这只会保存 ipython 历史的特定会话,但不会保存 ipython 命令的整个历史。

于 2020-02-28T21:12:12.380 回答
0

使用纯文本文件来存储历史记录会导致来自不同会话的命令被交错,并且会使添加诸如“从 session-x 运行第三个命令”或在历史记录中搜索等功能变得过于复杂和缓慢。因此 sqlite 数据库,

尽管如此,将脚本转储历史写入文件并同时进行统计应该很容易。你对文本文件所做的一切都应该用 sqlite 来实现。

于 2013-05-31T14:57:03.763 回答