環境変数 PYTHONSTARTUP の目的

環境構築
python
Author

Ryo Nakagami

Published

2025-08-02

Modified

2025-09-10

シェル環境変数としての PYTHONSTARTUP

Definition 1 PYTHONSTARTUP

  • PYTHONSTARTUP はインタラクティブモードのPythonを起動する直前に読み込むPythonスクリプトのPATHを示す環境変数
  • インタラクティブモードPythonのための設定なので,通常は .zshrc / .bashrc で定義

設定内容例

  • インタラクティブモードのコマンド履歴格納ファイル .python_history のPATH設定
  • 起動時に .python_history に書き込むラインの設定(例: 起動時刻を履歴ファイルに書き込む)
  • 起動時に自動的に読み込むモジュールの設定(例: 常に import numpy as np を実行する)

個人用設定

方針

  1. セッション開始から終了までのコマンド履歴を格納する履歴ファイルの設定
  2. セッション開始時にタイムスタンプ付きのヘッダーを履歴ファイルに追加
  3. デフォルトで最大 10,000 行の履歴を履歴ファイルに保存

実装コード

モジュール 機能
import atexit プログラム終了時に特定の処理(ここでは履歴保存)を自動実行するためのモジュール
import readline Python の インタラクティブシェルで履歴や補完を扱うライブラリ
import os ファイルパス操作やディレクトリ作成など,OS 関連の処理に使用
#!/usr/bin/env python3

import atexit
import readline
import os
from datetime import datetime

# ==== create session header ====
date = datetime.now()
session_header = date.strftime("### Python session started on %Y-%m-%d %H:%M:%S ###")

# ==== save history file as ~/.cache/.python_history ====
histdir = os.path.expanduser("~/.cache/python")
os.makedirs(histdir, exist_ok=True)
histfile = os.path.join(histdir, ".python_history")

# ==== append session header to history file ====
with open(histfile, "a") as f:
    f.write(f"\n{session_header}\n")


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

# ==== register history saving function ====
atexit.register(readline.write_history_file, histfile)

シェル設定

~/.zshrc または ~/.bashrcPYTHONSTARTUP を追加:

export PYTHONSTARTUP=$HOME/.config/python/pythonstartup.py

コードの説明

履歴ファイルの保存場所設定

# ==== save history file as ~/.cache/.python_history ====
histdir = os.path.expanduser("~/.cache/python")
os.makedirs(histdir, exist_ok=True)
histfile = os.path.join(histdir, ".python_history")

~ はPythonのファイル操作では~という文字として認識してしまい,/home/<username> と解釈してくれません. os.path.expanduser を用いることで,クロスプラットフォーム対応ができる形で意図したPATH展開をしてくれます

セッションヘッダーを履歴ファイルに追記

# ==== append session header to history file ====
with open(histfile, "a") as f:
    f.write(f"\n{session_header}\n")
モード 説明 影響
"w" 書き込みモード.ファイルを 開いた時点で既存の内容を削除 履歴ファイルが完全に上書きされる.以前のコマンドもセッションヘッダーも消える
"a" 追記モード.既存の内容は残して末尾に書き込む 以前の履歴は保持される.新しいセッションヘッダーも追加される

履歴ファイルを読み込む

try:
    readline.read_history_file(histfile)
    readline.set_history_length(10000)
except FileNotFoundError:
    pass
コード 説明
readline.read_history_file(histfile) 既存の履歴ファイルを読み込むことで,前回までのコマンドが ↑↓キーで呼び出せるようになる.
readline.set_history_length(10000) 履歴の最大行数を 10,000行 に設定.古い履歴から順に削除される.
try ... except FileNotFoundError 履歴ファイルが存在しない場合でもエラーを出さず,スクリプトを継続できるようにする.

Python 終了時に履歴を保存

# ==== register history saving function ====
atexit.register(readline.write_history_file, histfile)
コード 説明
atexit.register(...) Python が終了するときに自動で指定関数を呼び出す
readline.write_history_file(histfile) 履セッション中に入力したコマンドを 履歴ファイルに書く.