天天看點

python中history()_如何為Python終端提供持久性曆史記錄

問題

有沒有辦法告訴互動式Python shell在會話之間保留其執行指令的曆史記錄?

當會話正在運作時,在執行指令之後,我可以向上箭頭并通路所述指令,我隻是想知道是否有某種方法可以儲存這些指令,直到下次我使用Python shell時。

這非常有用,因為我發現自己在會話中重用指令,這是我在上一個會話結束時使用的。

解決方案

當然你可以用一個小的啟動腳本。來自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

現在,在支援的系統上的互動式解釋器中預設啟用Tab-completion readline。預設情況下也會啟用曆史記錄,并将其寫入(并從中讀取)檔案~/.python-history。

以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援谷谷點程式。