Ubuntu & Python Shell: Code Completion

OK, so I know this is an old one, but one I felt is worth mentioning none the less.

Ubuntu does not, by default, have the PYTHONSTARTUP variable set – furthermore, the pythonstartup file does not exist initially either.  Fortunately, both of these ‘issues’ are easily resolved.

From bash,

you:~$ gedit .pythonstartup

Now to fill in your pythonstartup config file:

# pythonstartup
import os
import readline
import rlcompleter
import atexit
#Bind ‘TAB’ to complete
readline.parse_and_bind(‘tab:complete’)
#Set history file – ~.pythonhistory

histfile = os.path.join(os.environ[‘HOME’], ‘.pythonhistory’)
#Attempt read of histfile
try:
readline.read_history_file(histfile)
except IOError:
pass
#Write history file at shell exit
atexit.register(readline.write_history_file, histfile)
#Cleanup
del os, histfile, readline, rlcompleter

Now set your PYTHONSTARTUP var:

you:~$ export PYTHONSTARTUP=~/.pythonstartup

Now you are good to enter the Python Interactive Shell with CODE COMPLETION AND HISTORY!

Leave a comment

Your email address will not be published. Required fields are marked *