DEV Community

eLabFTW
eLabFTW

Posted on • Edited on

3

Improving the python REPL (autoload modules and history)

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

# 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
view raw pystartup hosted with ❤ by GitHub

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay