Tab-Complete and a Persistent History in Python
November 17, 2006 at 9:15 pm | Posted in python | 4 CommentsEarlier today, in #django on freenode, the topic of tab-complete in the python shell happened to come up – at first, I thought it wasn’t possible in standard python, and only in other python interpreters.
Thankfully, a link was posted with info on the readline and rlcomplete modules – at first, I couldn’t get their example working to load on startup, so upon further investigation, not only did I get that quirk worked out, but I stumbled across another module that lets you hook on start/exit to save/load a history file, much like bash.
Anyway, without any further ado, here’s the short and sweet version to get this setup:
import atexit import os historyPath = os.path.expanduser("~/.pyhistory") try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") if os.path.exists(historyPath): readline.read_history_file(historyPath) def save_history(historyPath=historyPath): try: import readline except ImportError: print "Module readline not available." else: readline.write_history_file(historyPath) atexit.register(save_history)
Drop that in a file such as .pythonrc in your home directory, then point python to that by adding the path to the PYTHONSTARTUP environment variable in .bashrc or .bash_profile
4 Comments
Sorry, the comment form is closed at this time.
Blog at WordPress.com.
Entries and comments feeds.
Why not use ipython? http://ipython.scipy.org/
I was using the method described above until I came across ipython which seems to tie all this functionality up into a very nice command repl.
Comment by Russ— November 25, 2006 #
Mainly because I don’t control all the servers I use python on, so I can’t just go installing another interpreter š
Comment by Collin— November 25, 2006 #
ipython isn’t another shell — it’s a wrapper script. All it does is:
#!/usr/bin/python2.x
import IPython
IPython.Shell.start().mainloop()
Also, ipython is quite honestly the best enhancement to the python shell you can make. š
Comment by thalin— April 4, 2007 #
You may want to add a
readline.set_history_length(1000)
line before thereadline.write_history_file(historyPath)
to limit the history file to 1000 (or whatever other number you’d like) lines.Comment by Todd O'Bryan— November 14, 2007 #