From 5bbbfb06328ddf59135e797ee56417bb0ee00143 Mon Sep 17 00:00:00 2001 From: Fernando Schauenburg Date: Sun, 3 Nov 2019 02:52:18 +0100 Subject: [PATCH] Replace ~/.python_history with $XDG_CACHE_HOME/python/history --- dotfiles/.config/bash/profile | 2 +- dotfiles/.config/python/startup.py | 28 ++++++++++++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/dotfiles/.config/bash/profile b/dotfiles/.config/bash/profile index c46bc98..8f4d798 100644 --- a/dotfiles/.config/bash/profile +++ b/dotfiles/.config/bash/profile @@ -19,9 +19,9 @@ export LESS="-i -j.49 -M -R -z-2" export LESSHISTFILE="$XDG_CACHE_HOME/less/history" export LESSHISTSIZE=1000 export PAGER=less +export PYTHONSTARTUP="$XDG_CONFIG_HOME/python/startup.py" export VIMINIT='let $MYVIMRC="$XDG_CONFIG_HOME/vim/vimrc" | source $MYVIMRC' - # Find out where Homebrew performs installations. If Homebrew is not # installed (e.g. running on Linux), assume /usr/local for our # installations. diff --git a/dotfiles/.config/python/startup.py b/dotfiles/.config/python/startup.py index e9992b0..ca9a82a 100644 --- a/dotfiles/.config/python/startup.py +++ b/dotfiles/.config/python/startup.py @@ -1,13 +1,14 @@ -import sys - """Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. -If the readline module can be imported, the hook will set the Tab key -as completion key and register ~/.python_history as history file. -This can be overridden in the sitecustomize or usercustomize module, -or in a PYTHONSTARTUP file. +If the readline module can be imported, the hook will set the Tab key as +completion key and register a history file, using +$XDG_CACHE_HOME/python/history if XDG_CACHE_HOME iset and .python_history +otherwise. """ +import os +import sys + def register_readline(): import atexit try: @@ -39,8 +40,11 @@ def register_readline(): # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 - history = os.path.join(os.path.expanduser('~'), - '.python_history') + + history = os.path.join(os.path.expanduser('~'), '.python_history') + if 'XDG_CACHE_HOME' in os.environ: + history = os.path.join(os.environ['XDG_CACHE_HOME'], 'python', 'history') + try: readline.read_history_file(history) except OSError: @@ -48,9 +52,13 @@ def register_readline(): def write_history(): try: + history_dir = os.path.dirname(history) + if not os.path.isdir(history_dir): + os.makedirs(history_dir) + readline.write_history_file(history) - except (FileNotFoundError, PermissionError): - # home directory does not exist or is not writable + except (FileNotFoundError, PermissionError, OSError): + # history file does not exist or is not writable # https://bugs.python.org/issue19891 pass