繁体   English   中英

在ipython历史中搜索

[英]Search inside ipython history

ipython%his命令输出用户输入的最近命令。 是否可以在这些命令中搜索? 像这样的东西:

[c for c in %history if c.startswith('plot')]

编辑我不是在寻找重新运行命令的方法,而是在历史列表中找到它。 当然,有时我会想要在找到命令后重新运行命令,无论是逐字还是修改。

使用ctr-r 编辑搜索然后键入plot将显示以“plot”开头的最新命令。 它不会列出以它开头的所有命令。 你也不能在命令的中间或末尾搜索

在这里扩展PreludeAndFugue的解决方案我正在寻找:

[l for l in  _ih if l.startswith('plot')]

在这里, if条件可以用正则表达式代替

更好的是: %hist -g pattern影响你过去的pattern历史。 您还可以将搜索范围限制为当前会话或特定范围的行。 %hist?

所以对于@ BorisGorelik的问题,您必须这样做

%hist -g plot

不幸的是你做不到

%hist -g ^plot

也不

%hist -g "^plot"

如果要在历史记录中重新运行命令,请尝试Ctrl-r ,然后尝试搜索字符串。

我经常发现自己想在所有之前和当前会话中搜索整个ipython历史记录。 为此,我使用:

from IPython.core.history import HistoryAccessor
hista = HistoryAccessor()
z1 = hista.search('*numpy*corr*')
z1.fetchall()

或者 (不要同时运行或者你会破坏/删除你的历史)

ip = get_ipython()
sqlite_cursor = ip.history_manager.search('*numpy*corr*')
sqlite_cursor.fetchall()

搜索字符串不是正则表达式。 iPython history_manager使用sqlite的glob *搜索语法。

与第一个答案类似,您可以执行以下操作:

''.join(_ih).split('\n')

但是,在遍历命令历史记录项时,您可以执行以下操作。 因此,您可以从中创建列表理解。

for item in _ih:
    print item

这在文档的以下部分中有记录: http//ipython.org/ipython-doc/dev/interactive/reference.html#input-caching-system

你有办法做到这一点:

''.join(_ip.IP.shell.input_hist).split('\n')

要么

''.join(_ip.IP.shell.input_hist_raw).split('\n')

防止magick扩张。

from IPython.core.history import HistoryAccessor


def search_hist(pattern,
                print_matches=True,
                return_matches=True,
                wildcard=True):

    if wildcard:
        pattern = '*' + pattern + '*'
    matches = HistoryAccessor().search(pattern).fetchall()

    if not print_matches:
        return matches

    for i in matches:
        print('#' * 60)
        print(i[-1])

    if return_matches:
        return matches
%history [-n] [-o] [-p] [-t] [-f FILENAME] [-g [PATTERN [PATTERN ...]]]
         [-l [LIMIT]] [-u]
         [range [range ...]]

....

-g <[PATTERN [PATTERN …]]>
treat the arg as a glob pattern to search for in (full) history. This includes the saved history (almost all commands ever written). The pattern may contain ‘?’ to match one unknown character and ‘*’ to match any number of unknown characters. Use ‘%hist -g’ to show full saved history (may be very long).

示例(在我的历史中):

In [23]: hist -g cliente*aza
655/58: cliente.test.alguna.update({"orden" : 1, "nuevo" : "azafran"})
655/59: cliente.test.alguna.update({"orden" : 1} , {$set : "nuevo" : "azafran"})
655/60: cliente.test.alguna.update({"orden" : 1} , {$set : {"nuevo" : "azafran"}})

示例(在我的历史中):

In [24]: hist -g ?lie*aza
655/58: cliente.test.alguna.update({"orden" : 1, "nuevo" : "azafran"})
655/59: cliente.test.alguna.update({"orden" : 1} , {$set : "nuevo" : "azafran"})
655/60: cliente.test.alguna.update({"orden" : 1} , {$set : {"nuevo" : "azafran"}})

暂无
暂无

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

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