溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么為Python終端提供持久性歷史記錄

發(fā)布時(shí)間:2021-02-03 11:10:10 來源:億速云 閱讀:154 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹怎么為Python終端提供持久性歷史記錄,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

問題

有沒有辦法告訴交互式Python shell在會(huì)話之間保留其執(zhí)行命令的歷史記錄?

當(dāng)會(huì)話正在運(yùn)行時(shí),在執(zhí)行命令之后,我可以向上箭頭并訪問所述命令,我只是想知道是否有某種方法可以保存這些命令,直到下次我使用Python shell時(shí)。

這非常有用,因?yàn)槲野l(fā)現(xiàn)自己在會(huì)話中重用命令,這是我在上一個(gè)會(huì)話結(jié)束時(shí)使用的。

解決方案

當(dāng)然你可以用一個(gè)小的啟動(dòng)腳本。來自python教程中的交互式輸入編輯和歷史替換:

# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=~/.pystartup" in bash.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
  import readline
  readline.write_history_file(historyPath)

if os.path.exists(historyPath):
  readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath

從Python 3.4開始,交互式解釋器支持開箱即用的自動(dòng)完成和歷史記錄:

現(xiàn)在,在支持的系統(tǒng)上的交互式解釋器中默認(rèn)啟用Tab-completion readline。默認(rèn)情況下也會(huì)啟用歷史記錄,并將其寫入(并從中讀?。┪募/.python-history。

以上是“怎么為Python終端提供持久性歷史記錄”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI