通過深入研究IPython,篩選解釋不當和/或已棄用的文檔,我將一個似乎工作正常的解決方案拼湊在一起,儘管我確定它不是最佳的,原因有很多,即:
- 它運行
history
數據庫上GROUP BY
查詢每次運行在IPython中一行
- 不小心清理/協調數據庫表的時間 - 我只修改
history
,卻忽略output_history
和sessions
表格
我把下面的一個文件(我把它命名爲dedupe_history.py
,但名字是無關緊要的)內部$HOME/.ipython/profile_default/startup
:
import IPython
import IPython.core.history as H
## spews a UserWarning about locate_profile() ... seems safe to ignore
HISTORY = H.HistoryAccessor()
def dedupe_history():
query = ("DELETE FROM history WHERE rowid NOT IN "
"(SELECT MAX(rowid) FROM history GROUP BY source)")
db = HISTORY.db
db.execute(query)
db.commit()
def set_pre_run_cell_event():
IPython.get_ipython().events.register("pre_run_cell", dedupe_history)
## dedupe history at start of new session - maybe that's sufficient, YMMV
dedupe_history()
## run dedupe history every time you run a command
set_pre_run_cell_event()