b3nj5m1n/xdg-ninja

Python recommendation returns an error when you exit ipython

Closed this issue · 3 comments

I followed the recommendation for removing .python_history, and when I exit ipython, I get the following error message, and then ipython exits.

Exception ignored in atexit callback: <function write_history at 0x7ff4c0737420>
Traceback (most recent call last):
  File "/etc/python/pythonrc", line 27, in write_history
    readline.write_history_file(history)
    ^^^^^^^^
NameError: name 'readline' is not defined

This seems like a weird result, given that the python file should be valid and readline should never be undefined, unless it's reading that file differently than normal python.

Python 3.11
IPython 8.14.0

iuuky commented

Write the following into $XDG_CONFIG_HOME/python/pythonrc:

#!/usr/bin/env python3

def is_vanilla() -> bool:
	""" :return: whether running "vanilla" Python """
	import sys
	return not hasattr(__builtins__, '__IPYTHON__') and 'bpython' not in sys.argv[0]


def setup_history():
	""" read and write history from state file """
	import os
	import atexit
	import readline
	from pathlib import Path

	# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
	if state_home := os.environ.get('XDG_STATE_HOME'):
		state_home = Path(state_home)
	else:
		state_home = Path.home() / '.local' / 'state'

	history: Path = state_home / 'python_history'

	readline.read_history_file(str(history))
	atexit.register(readline.write_history_file, str(history))


if is_vanilla():
	setup_history()

Then create an empty file for the history, in my case, it's in $XDG_STATE_HOME/python_history.

Er, hi, hello. I'm using xdg-ninja to clean up my home directory, and this issue was linked from it, so I thought I would come here. The suggestion for dealing with python is... actually way worse than the status quo? The solution to dealing with a hidden-by-default dotfile is to create a non-hidden directory? I don't have a python directory in $HOME, so why would I want to do that?

@HugLifeTiZ I think the suggestion is just wrong, perhaps an oversight. It should have been $XDG_CONFIG_HOME instead:

export PYTHONSTARTUP="$HOME"/python/pythonrc

to become

export PYTHONSTARTUP="$XDG_CONFIG_HOME"/python/pythonrc