• programming in python • a course for the curious •

Completion for Python Console

There are several ways how you can make your life easier using the Python console. For example you can switch on code completion: hitting enter you will get completion of your variable, object name, class name, or a built-in function. It also supports the name spaces of imported modules. Here I will guide you how to do that.

First create an environment variable $PYTHONSTARTUP and give it the value '$HOME/.pystartup'. Now add the follwing content to this file:

  1. import atexit
  2. import os
  3. import os.path
  4. import sys
  5. import readline
  6. import rlcompleter
  7. historyPath = os.path.expanduser("~/.pyhistory")
  8. def save_history(historyPath=historyPath):
  9. import readline
  10. readline.write_history_file(historyPath)
  11. if os.path.exists(historyPath):
  12. readline.read_history_file(historyPath)
  13. atexit.register(save_history)
  14. del atexit, readline, save_history, historyPath, rlcompleter

You can enhance the rlcompleter if you want just subclass the rlcompleter.Completer object and rewrite its complete method. For example you can add completion for the import statement. This is a fun thing to do!

You can also use the $PYTHONSTARTUP file to load modules which you often use. For example the above script is not deleting the modules os, os.path and sys. Now you got the Tab completion which is a cool feature of IPython, though the Python console starts a way faster!

Contact us.
Created using , and
we are not associated with Python Software Foundation
© Copyright 2012, 2013 Accorda Institute.