![`~/.python_history` 위치 변경](https://linux55.com/image/186887/%60~%2F.python_history%60%20%EC%9C%84%EC%B9%98%20%EB%B3%80%EA%B2%BD.png)
기능은 유지하고 싶지만 위치 ~/.python_history
를 $XDG_DATA_HOME/python/python_history
.
이것나에게 다음과 같은 아이디어를 주었습니다. 나는 그것을 만들고 $XDG_CONFIG_HOME/python/pythonrc
가리킬 수 있습니다 $PYTHONSTARTUP
. 거기 에서 함수 를 교체하고 싶습니다 readline.read_history_file
.readline.write_history_file
readline.append_history_file
이러한 함수를 사용자 정의 매개변수가 포함된 함수 자체로 대체할 수 있는 방법이 있습니까 filename
?
그렇지 않다면 이 문제를 해결하는 방법에 대한 다른 아이디어가 있습니까?
답변1
당신과 ctrl-alt-delor처럼 나도 신비롭고 깨끗한 홈 디렉토리를 찾습니다. readline.write_history_file
종료 시 실행되도록 등록 하는 호출은 site.py
다음과 같습니다(내 아치 시스템에서는 /usr/lib/python3.9/site.py
).
if readline.get_current_history_length() == 0:
# If no history was loaded, default to .python_history.
# The guard is necessary to avoid doubling history size at
# 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')
try:
readline.read_history_file(history)
except OSError:
pass
def write_history():
try:
readline.write_history_file(history)
except OSError:
# bpo-19891, bpo-41193: Home directory does not exist
# or is not writable, or the filesystem is read-only.
pass
atexit.register(write_history)
PYTHONSTARUP에서 이를 복제할 수 있지만 Python 기록에 대한 사용자 정의 위치를 사용합니다. 이것은 내 것입니다(하지만 원하는 경우 환경 대체를 사용하여 적절한 XDG 디렉토리를 사용할 수 있다고 확신합니다.:
import os
import atexit
import readline
history = os.path.join(os.path.expanduser('~'), '.cache/python_history')
try:
readline.read_history_file(history)
except OSError:
pass
def write_history():
try:
readline.write_history_file(history)
except OSError:
pass
atexit.register(write_history)
너할 수 있다write_history_file 함수를 재정의하지만 이는 매우 구식이므로(사용자 정의 인수 대신 제공하는 인수를 무시해야 함) 이것이 최선의 해결책이라고 생각합니다. 이것이 작동하지 않으면 사용자 정의 Python 기록 파일에 더미 항목을 만들어 기록 길이가 0보다 커지도록 시도해 보세요.
답변2
유일한 사람xdg-ninja
목적(편의를 위해 여기에 붙여넣음):
환경 변수 내보내기:
export PYTHONSTARTUP="/etc/python/pythonrc"
만들다 /etc/python/pythonrc
:
import os
import atexit
import readline
from pathlib import Path
if readline.get_current_history_length() == 0:
state_home = os.environ.get("XDG_STATE_HOME")
if state_home is None:
state_home = Path.home() / ".local" / "state"
else:
state_home = Path(state_home)
history_path = state_home / "python_history"
if history_path.is_dir():
raise OSError(f"'{history_path}' cannot be a directory")
history = str(history_path)
try:
readline.read_history_file(history)
except OSError: # Non existent
pass
def write_history():
try:
readline.write_history_file(history)
except OSError:
pass
atexit.register(write_history)
답변3
이는 Python 3.13에서 병합하여 구현됩니다.PR13208. PYTHON_HISTORY
기록 파일의 위치를 사용자 정의하는 데 사용할 수 있는 환경 변수를 추가합니다 .
export PYTHON_HISTORY=~/.local/share/python/history
답변4
이에 대한 나의 견해는 다음에서 영감을 받았습니다.다른 답변:
# Enable custom ~/.python_history location on Python interactive console
# Set PYTHONSTARTUP to this file on ~/.profile or similar for this to work
# https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP
# https://docs.python.org/3/library/readline.html#example
# https://github.com/python/cpython/blob/main/Lib/site.py @ enablerlcompleter()
# https://unix.stackexchange.com/a/675631/4919
import atexit
import os
import readline
import time
def write_history(path):
import os
import readline
try:
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
readline.write_history_file(path)
except OSError:
pass
history = os.path.join(os.environ.get('XDG_CACHE_HOME') or
os.path.expanduser('~/.cache'),
'python_history')
try:
readline.read_history_file(history)
except FileNotFoundError:
pass
# Prevents creation of default history if custom is empty
if readline.get_current_history_length() == 0:
readline.add_history(f'# History created at {time.asctime()}')
atexit.register(write_history, history)
del (atexit, os, readline, time, history, write_history)