Fork me on GitHub

Python interpreter autocomplete + history with ~/.pythonrc

Python interpreter autocomplete + history with ~/.pythonrc

Using great tools is important, using autocompletion with great tools is even better. Update: use Jupyter, it’s just amazing!

Never used python interpreter?

Try it now! Install python if it’s not already the case and run python in a terminal. There you go, you’re now inside a python interpreter!

Bare python interpreter example

Get interpreter autocompletion and history

Here is what you’re looking for, create this file:

~/.pythonrc

import atexit, os, sys, readline, rlcompleter

readline.parse_and_bind('tab:complete')

print(".pythonrc :: AutoCompletion Loaded")

# History
historyPath = os.path.expanduser("~/.pyhistory")


def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)
    print(".pythonrc :: history saved to " + historyPath)

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)

Then, you need to tell python interpreter to use this ~/.pythonrc file, so add the following line somewhere in an rc file (either ~/.bashrc if you’re using bash or ~/.zshrc for the awesome oh-my-zsh)

export PYTHONSTARTUP=~/.pythonrc

You can also run this directly in your shell if you want to test before editing your rc file.

That’s it, fire up a terminal, run python again and enjoy autocompletion when you hit tab key :D

pythonrc terminal example

All of the commands you type in a local interpreter are now recorded to ~/.pyhistory. Hit tab when experimenting with modules from the interwebs and it will be much easier to discover all the things :)

Want more?

For advanced usage, there are a few interpreters available that provide features out of the box such as syntax highlighting while you type:

I used IPython for a while and it’s great:

IPython usage example

Even better, use Jupyter

Jupyter lets you manage notebooks with live code, syntax highlighting, visualizations, markdown and even has a few extensions. It’s really worth the try.

pip3 install jupyter
jupyter notebook

You’ll love it and it’s even more fun when used with numpy and matplotlib.

jupyter localhost example

Oh and you can save them as gists which is wonderful for sharing and embedding:

Neat eh?


Found a typo? Have a suggestion? Open an issue or send me a pull-request!



Metrics Watch

helping me with Google Analytics.