preserve history in the interactive python

Nikhil mnikhil at gmail.com
Tue May 20 14:19:17 EDT 2008


Nikhil wrote:
> Hi,
> 
> I am using python -i, and I find it hard typing/pasting the commands 
> from the previous interactive shell. Basically, is there anyway that I 
> can preserve the history in the shell?
> I guess but not sure there should be something like ~/.pyrc for 
> configuring such but can someone please let me know what is the 
> effective environment variable to preserve the history?
> 
> Thanks,
> Nikhil
I figured it out. This below thing works fine for me.
BTW, I got it from http://docs.python.org/tut/node15.html. A little 
search would not hurt ;-)


$ echo $PYTHONSTARTUP
/u/me/.pyrc
$ cat .pyrc
import sys
import atexit
import os
import readline
import rlcompleter

myprompt='$ '
myhistoryfile="/u/me/.pyhistory"

#set the prompt
sys.ps1=myprompt

#save the history
historyPath = os.path.expanduser(myhistoryfile)

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



More information about the Python-list mailing list