如何将IPython历史记录到文本文件?

l0b*_*0b0 15 python configuration ipython

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

这对于控制常用命令的版本非常好,例如.bash_history.

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

Chr*_*ong 35

您可以将IPython中的所有历史记录导出为这样的文本文件.

%history -g -f filename
Run Code Online (Sandbox Code Playgroud)

获得你想要的东西的一种方法可能是在git钩子中进行导出.我通常将这些"同步外部资源"操作放在post-checkout git hook中.

  • 运行`?%history`还会显示如何提取日志的特定部分,如活动会话. (3认同)

Pra*_*iel 10

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

%history 1 7-8 10 -f /tmp/bar.py
Run Code Online (Sandbox Code Playgroud)

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

%history -f /tmp/foo.py
Run Code Online (Sandbox Code Playgroud)


min*_*nrk 7

您可以通过在启动脚本之一中添加bash来模拟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)
Run Code Online (Sandbox Code Playgroud)

请注意,这会模拟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()
Run Code Online (Sandbox Code Playgroud)

将其放在您的profile_default/startup/目录中,然后编辑profile_default/readline_favorites,或在您希望保留该文件的任何位置,它将在每个IPython会话中以readline补全等形式显示。


Q2L*_*arn 7

To save a Ipython session history:

%save [filename] [line start - line end] 
Run Code Online (Sandbox Code Playgroud)

For example:

%save ~/Desktop/Ipython_session.txt 1-31
Run Code Online (Sandbox Code Playgroud)

This will only save that particular session of ipython history but will not save the entire history of ipython commands.