LoginSignup
1
0

More than 1 year has passed since last update.

~/.python_history の場所を変更する

Last updated at Posted at 2022-08-23

ホームディレクトリに存在する.python_historyの場所を変更する方法を紹介します.

この投稿の概要

  • .python_historyは Python の対話モードの履歴を記録するファイル
  • デフォルトの設定では,ホームディレクトリに保存される
  • ホームディレクトリに dotfiles が多く存在する状況は気持ちが悪い
  • 本稿では,.python_historyの保存場所を変更する方法について紹介

環境

  • macOS 12.5.1 Monterey (2022 M2 MacBook Air)
  • Python 3.10.6 (バージョン管理ツール asdf でインストール)
  • zsh 5.8.1 (x86_64-apple-darwin21.0)

本稿では,macOS を対象として説明します.
ですが,Linux においても同様の方法が適用可能だと思われます.

やること

  • 環境変数PYTHONSTARTUPにインタプリタ起動時に自動で読み込むスクリプトを設定
  • 今回は,~/.config/python/pythonstartup.pyをスクリプトとして指定
.zshrc
export PYTHONSTARTUP=$HOME/.config/python/pythonstartup.py
  • ~/.config/python/pythonstartup.pyに以下を記述
  • 以下では,~/.cache/.python_historyを履歴保存場所に変更
pythonstartup.py
#!/usr/bin/env python3

import atexit
import readline
import os

# save history file as ~/.cache/.python_history
histfile = os.path.join(os.path.expanduser('~/.cache'), '.python_history')

try:
    readline.read_history_file(histfile)
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)
  • シェルを再起動して,pythonを起動すると~/.cache/.python_historyに履歴が保存されるようになる

参考文献

Python 3.10.6 Documentation
Unix & Linux Stack Exchages
まくまくの Python ノート

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0