简体   繁体   English

Python相当于ignoreboth:erasedups

[英]Python equivalent of ignoreboth:erasedups

I'm running iPython (Jupyter) through Anaconda, on a Mac Sierra, through iTerm, with $SHELL=bash - if I've missed any helpful set up details, just let me know. 我正在通过Anaconda运行iPython(Jupyter),在Mac Sierra上通过iTerm,使用$SHELL=bash - 如果我错过了任何有用的设置细节,请告诉我。

I love the $HISTCONTROL aspect of bash , mentioned here . 我喜欢这里提到的bash$HISTCONTROL方面。 To sum that answer up: when traversing history (aka hitting the up arrow), it's helpful to remove duplicate entries so you don't scroll past the same command multiple times, and this is accomplished with $HISTCONTROL=ignoreboth:erasedups . 总结一下这个答案:当遍历历史记录(也就是点击向上箭头)时,删除重复的条目是有帮助的,这样你就不会多次$HISTCONTROL=ignoreboth:erasedups同一个命令,而这是用$HISTCONTROL=ignoreboth:erasedups

Is there any equivalent for this inside the Python interpreter (or iPython, specifically)? 在Python解释器(或iPython,特别是)中是否有相应的内容? I have readline installed and feel like that's a good place to start, but nothing jumped out as obviously solving the problem, and I would've thought this was built in somewhere. 我已经安装了readline并且感觉这是一个很好的起点,但没有任何东西突然解决问题,我会认为这是在某个地方构建的。

Through some deep-diving into IPython, sifting through poorly-explained and/or deprecated documentation, I've pieced together a solution that seems to work fine, though I'm sure it's not optimal for a number of reasons, namely: 通过对IPython的深入研究,筛选出解读不当和/或弃用的文档,我拼凑了一个似乎工作正常的解决方案,尽管我确信它不是最优的,原因有很多,即:

  • it runs a GROUP BY query on the history database every time I run a line in IPython 每次我在IPython中运行一行时,它都会在history数据库上运行GROUP BY查询
  • it doesn't take care to clean up/coordinate the database tables - I only modify history , but ignore output_history and sessions tables 它没有注意清理/协调数据库表 - 我只修改history ,但忽略output_historysessions

I put the following in a file (I named it dedupe_history.py , but name is irrelevant) inside $HOME/.ipython/profile_default/startup : 我将以下内容放在$HOME/.ipython/profile_default/startup中的文件中(我将其命名为dedupe_history.py ,但名称无关紧要):

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM