簡體   English   中英

如何將 IPython 歷史記錄到文本文件?

[英]How to log IPython history to text file?

在對 IPython文檔和一些代碼進行了一些搜索和瀏覽之后,我似乎無法弄清楚是否可以將命令歷史記錄(而不是輸出日志)存儲到文本文件而不是 SQLite 數據庫。 ipython --help-all似乎表明此選項不存在。

這對於像.bash_history這樣的常用命令進行版本控制非常好。

編輯:基於@minrk 的答案的工作解決方案

您可以使用%history魔法將 IPython 中的所有歷史記錄導出到文本文件,如下所示:

%history -g -f filename

獲得所需內容的一種方法可能是在git hook中進行導出。 我通常將這些“同步外部資源”操作放在結帳后的 git 鈎子中。

您還可以選擇要保存的行。 例如

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

這會將第 1、7 到 8 和 10 行保存到臨時文件 bar.py。 如果您需要整個,請跳過該行的一部分。

%history -f /tmp/foo.py

您可以通過在您的啟動腳本之一(例如$(ipython locate profile)/startup/log_history.py添加它來模擬 bash 的行為:

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 完成等中顯示。

要保存 Ipython 會話歷史記錄:

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

例如:

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

這只會保存 ipython 歷史的特定會話,但不會保存 ipython 命令的整個歷史。

使用純文本文件來存儲歷史會導致來自不同會話的命令被交錯,並且使添加諸如“從 session-x 運行第三個命令”或在歷史中搜索等功能變得過於復雜和緩慢。 因此,sqlite 數據庫,

盡管如此,將腳本轉儲歷史記錄寫入文件並同時執行 stat 應該很容易。 你對文本文件所做的一切都應該可以用 sqlite 來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM