Improving the python REPL (autoload modules and history)

eLabFTW - Oct 24 '18 - - Dev Community

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.

python

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

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

. . . . . .