Hello to you dear reader,
When doing python code, it might be useful to fire up the REPL (Read-Eval-Print-Loop) by simply typing python
in a terminal to test some expressions.
But the problem is that it is very barebone. No history, no modules loaded by default. I don't know about you but 99% of the time I'll need to use numpy
and pandas
at the minimum. Probably matplotlib
too.
Who has time to type import xyz
every time? Not me.
So here is how to autoload modules in python's REPL:
Start by creating a ~/.pystartup file
# Add auto-completion and a stored history file of commands to your Python | |
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is | |
# bound to the Esc key by default (you can change it - see readline docs). | |
# | |
# Store the file in ~/.pystartup, and set an environment variable to point | |
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash. | |
# | |
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the | |
# full path to your home directory. | |
import atexit | |
import os | |
import readline | |
import rlcompleter | |
import numpy as np | |
import skimage.io | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
historyPath = os.path.expanduser("~/.pyhistory") | |
def save_history(historyPath=historyPath): | |
import readline | |
readline.write_history_file(historyPath) | |
if os.path.exists(historyPath): | |
readline.read_history_file(historyPath) | |
atexit.register(save_history) | |
del os, atexit, readline, rlcompleter, save_history, historyPath |
As you can see, this file will also configure the ~/.pyhistory
file so python doesn't forget everything when you close the REPL.
It is recommended to install these often used modules with pip install --user module-name
, see my previous post: Stop using sudo pip install
Configure the PYTHONSTARTUP env var
Add this to your ~/.zshrc, ~/.fishrc, ~/.bashrc or whatever you use:
# Note that '~' is not expanded, so use the full path here
export PYTHONSTARTUP=/home/user/.pystartup
That's it, now try again to fire up python
and check that the modules are there.
There you go :) Now go write so amazing code!
Cheers,
~Nico
Top comments (0)