From 82d15915515ed2c0dbe7891acb8f049a06e9b7a2 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Sat, 30 Aug 2025 12:09:41 +0200 Subject: [PATCH] Add configuration for `python` Move Python's history into ~/.local/state/python --- .config/python/startup.py | 53 ++++++++++++++++++++++++++++++++++++ .config/shell/env | 2 ++ .local/state/python/.gitkeep | 0 3 files changed, 55 insertions(+) create mode 100644 .config/python/startup.py create mode 100644 .local/state/python/.gitkeep diff --git a/.config/python/startup.py b/.config/python/startup.py new file mode 100644 index 0000000..9c1a938 --- /dev/null +++ b/.config/python/startup.py @@ -0,0 +1,53 @@ +"""Move Python's history file to "$XDG_STATE_HOME/python/history".""" + +import atexit +import os +import readline +import sys + + +# For Python 3.13+ let `$PYTHON_HISTORY` handle it +if sys.version_info >= (3, 13): + sys.exit(0) + + +# For Python 2, do nothing +try: + import pathlib +except ImportError: + sys.exit(0) + + +if readline.get_current_history_length() == 0: + state_home = os.environ.get("XDG_STATE_HOME") + + if state_home is None: + state_home = pathlib.Path.home() / ".local" / "state" + else: + state_home = pathlib.Path(state_home) + + history_path = state_home / "python" / "history" + history_path.parent.mkdir(parents=True, exist_ok=True) + + history_location = str(history_path) + + if history_path.is_dir(): + msg = history_location + " must not be a directory" + raise OSError(msg) + + try: + readline.read_history_file(history_location) + except OSError: # Non existent + pass + + readline.set_auto_history() + readline.set_history_length(99999) + + def write_history(): + try: + readline.write_history_file(history_location) + except OSError: + pass + + atexit.register(write_history) + diff --git a/.config/shell/env b/.config/shell/env index 76326ed..b1f9a2d 100644 --- a/.config/shell/env +++ b/.config/shell/env @@ -30,4 +30,6 @@ export VISUAL=$EDITOR export BAT_CONFIG_PATH="$XDG_CONFIG_HOME/bat/config" export LESSHISTFILE="$XDG_STATE_HOME/less/history" export PSQLRC="$XDG_CONFIG_HOME/psql/psqlrc" +export PYTHON_HISTORY="$XDG_STATE_HOME/python/history" +export PYTHONSTARTUP="$XDG_CONFIG_HOME/python/startup.py" export VIMINIT="source $XDG_CONFIG_HOME/vim/vimrc" diff --git a/.local/state/python/.gitkeep b/.local/state/python/.gitkeep new file mode 100644 index 0000000..e69de29