brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: PYTHONSTARTUP loads your own helpers into every Python prompt

Python
~/tips/tip-python-pythonstartup-repl

import json, os, re, sys

Run a file of imports and helpers each time you open the interactive Python prompt.

If you open the Python prompt as a calculator and for quick checks, typing the same imports every time gets old. PYTHONSTARTUP runs a file of your choosing first.

# ~/.pythonstartup.py
import json, os, re, sys
from pathlib import Path
from pprint import pp

# in ~/.bashrc or ~/.zshrc
export PYTHONSTARTUP=~/.pythonstartup.py

Open a new shell, type python3 and those modules are already imported. The file runs in the same namespace as the prompt, so anything it defines, like a small helper that loads a JSON file, is ready to use.

It only kicks in for interactive sessions. Scripts, python3 -c and python3 -m ignore it, so your startup file can’t accidentally change how real programs behave. That’s exactly why I’m comfortable putting things there.

Keep the file fast and safe. A slow import in it delays every prompt you open, and an error prints a traceback each time. It also runs for every Python you start from that shell, including the ones in your venvs, so an import of a package that isn’t installed there will fail. Wrapping those imports in try/except ImportError avoids the noise.

Further reading: PYTHONSTARTUP

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link