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:
history_file = os.path.expanduser(‘~/.python_history’)
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:
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.
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 PYTHONSTARTUP.
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:
history = os.path.expanduser(‘~/.python_history’)