簡體   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