History and TAB completion in the Python interpreter
From IlugCal
Contents |
[edit] Introduction
The idea is to save the command history between multiple sessions of the Python interpreter, and provide TAB completion against the names of objects in the current namespace. We will be using the two successive hits of the ESC key instead of the TAB key to perform TAB completion, since the TAB key is very convenient for indenting the commands in interactive mode.
[edit] Create the Startup File
Create a file (say /etc/pythonrc or ~/.pythonrc) and dump the following body of code into it.
try:
import readline
except ImportError:
print "Module readline not available."
else:
import atexit
import os
import rlcompleter
historyPath = os.path.expanduser("~/.python_history")
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
[edit] Edit the Environment
Set the environment variable PYTHONSTARTUP to the name of the file you created in the above section. You may do so by putting a line similar to the following in your /etc/profile or ~/.bash_profile.
export PYTHONSTARTUP="/etc/pythonrc"
[edit] Enjoy
Log back into your account and start using the Python interpreter.
[edit] External Links
- http://docs.python.org/tut/tut.html Most of the material has been taken from this Python tutorial written by Guido van Rossum.

