Python shell history

image image

If you’re not a fan of enhanced Python interpreters like IPython or BPython but still do heavy use of it you might have notice how annoying it could get whenever you have to quit it, started again, and remember what was the last things you ran. I do this all the time, usually for simple things like testing out built-in functions or quick hacks.

PYTHONSTARTUP is an environment variable which value is the name of a readable file and is executed before the first prompt is displayed when starting the Python shell.

The following script creates a history file in youra home directory(similar to ~/.bash_history), on exit appends your latest work to this file, limits the number of entries saved to 1000, and as a bonus enables autocomplete on tab. 

After creating the file, you need to set the PYTHONSTARTUP environment variable. Best way is to add the following to your ~/.bash_profile.

export PYTHONSTARTUP=$HOME/.python-startup.py

Bonus: If you use Django, you can take advantage of your history file as well by using Django Extensions’ shell_plus with the –use-pythonrc flag.

python manage.py shell_plus --use-pythonrc