Every Python developer knows that the Python shell can speed up the work, but not anybody know how fast it can be.
In Bash you can browse the history of previously typed commands and have autocompletion with the tab key. Why not having the same features in the Python shell too?
On UNIX-like systems, Python is shipped with a really useful module in the standard library: readline that, among other things, can be used to enable the history. Its usage is very simple: it just needs a file to read and write the history, just like Bash. Here’s how it should be used:
>>> import os >>> import readline >>> history_file = os.path.expanduser('~/.python_history') >>> readline.read_history_file(history_file)
Note that the history file is not written automatically at exit: you ought to call
write_history_file() when you finish to use the interpreter or, better, register a function with atexit:
>>> import atexit >>> atexit.register(readline.write_history_file, history_file)
The readline module can be used for autocompletion too, but needs some help from a second module. In fact readline just binds the tab key, but the word completer itself is in rlcompleter.
>>> import rlcompleter >>> readline.parse_and_bind('tab: complete')
We have understood how to enable both history and autocompletion, but does this mean that we should type the above commands every time? No, of course. When used in interactive mode, Python always looks into the
PYTHONSTARTUP environment variable and executes the specified script, if any. So, you can put the code to enable history and autocompletion in a file (for example:
~/.pythonrc) and specify it in your
Using the RC file you also have the advantage that you can import the modules that you use frequently, so that you won’t have to import the manually in the interpreter. For example, here’s my own Python RC file:
import atexit import os import re import readline import rlcompleter import socket import _socket import sys import time import timeit history = os.path.expanduser('~/.python_history') readline.read_history_file(history) readline.parse_and_bind('tab: complete') atexit.register(readline.write_history_file, history) def t(*args): return timeit.Timer(*args).timeit()