Skip to content

Instantly share code, notes, and snippets.

@viliampucik
Created January 11, 2021 22:02
Show Gist options
  • Save viliampucik/8713b09ff7e4d984b29bfcd7804dc1f4 to your computer and use it in GitHub Desktop.
Save viliampucik/8713b09ff7e4d984b29bfcd7804dc1f4 to your computer and use it in GitHub Desktop.
XDG compliant ~/.python_history
# Store interactive Python shell history in ~/.cache/python_history
# instead of ~/.python_history.
#
# Create the following .config/pythonstartup.py file
# and export its path using PYTHONSTARTUP environment variable:
#
# export PYTHONSTARTUP="${XDG_CONFIG_HOME:-$HOME/.config}/pythonstartup.py"
import atexit
import os
import readline
histfile = os.path.join(os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")), "python_history")
try:
readline.read_history_file(histfile)
# default history len is -1 (infinite), which may grow unruly
readline.set_history_length(1000)
except FileNotFoundError:
pass
atexit.register(readline.write_history_file, histfile)
@smahm006
Copy link

@alichtman the script works ty. I just changed histfile to be in XDG_STATE_HOME as that is where I keep my less and bash history.

histfile = Path(os.getenv("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "python" / "python_history"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment