readline --- GNU readline のインターフェース


readline モジュールでは、補完や Python インタプリタからの履歴ファイルの読み書きを容易にするための多くの関数を定義しています。 このモジュールは直接、または rlcompleter モジュールを介して使うことができます。 rlcompleter モジュールは対話的プロンプトで Python 識別子の補完をサポートするものです。 このモジュールで利用される設定は、インタプリタの対話プロンプトならびに組み込みの input() 関数の両方の挙動に影響します。

readline のキーバインディングは初期化ファイルで設定できます。 このファイルは、たいていはホームディレクトリに .inputrc という名前で置いてあります。 GNU Readline マニュアルの Readline Init File を参照して、そのファイルの形式や可能な構成、 Readline ライブラリ全体の機能を知ってください。

利用可能な環境: not Android, not iOS, not WASI.

このモジュールは モバイルプラットフォーム と WebAssemblyプラットフォーム をサポートしません。

注釈

下層の Readline ライブラリー API は GNU readline ではなく editline (libedit) ライブラリーで実装される可能性があります。 macOS では readline モジュールはどのライブラリーが使われているかを実行時に検出します。

editline の設定ファイルは GNU readline のものとは異なります。 プログラムから設定文字列を読み込む場合は、backend で使用中のライブラリを判別できます。

macOS で editline/libedit による readline エミュレーションを使う場合、ホームディレクトリの初期化ファイル名は .editrc です。 例えば ~/.editrc に次の内容を書くと、vi のキーバインディングと TAB による補完が有効になります。

python:bind -v
python:bind ^I rl_complete

ライブラリによって履歴ファイルの形式が異なる場合もあります。 基盤となるライブラリを切り替えると、既存の履歴ファイルが使えなくなることがあります。

readline.backend

使用中の Readline ライブラリの名前で、"readline" または "editline" です。

Added in version 3.13.

初期化ファイル

以下の関数は初期化ファイルならびにユーザ設定関連のものです:

readline.parse_and_bind(string)

string 引数で渡された初期化行を実行します。 基盤となるライブラリの rl_parse_and_bind() を呼び出します。

readline.read_init_file([filename])

Execute a readline initialization file. The default filename is the last filename used. This calls rl_read_init_file() in the underlying library.

行バッファ

以下の関数は行バッファを操作します:

readline.get_line_buffer()

行バッファ (基盤となるライブラリの rl_line_buffer) の現在の内容を返します。

readline.insert_text(string)

カーソル位置の行バッファにテキストを挿入します。 基盤となるライブラリの rl_insert_text() を呼び出しますが、戻り値は無視します。

readline.redisplay()

行バッファの現在の内容が反映されるように画面表示を更新します。 基盤となるライブラリの rl_redisplay() を呼び出します。

履歴ファイル

以下の関数は履歴ファイルを操作します:

readline.read_history_file([filename])

Load a readline history file, and append it to the history list. The default filename is ~/.history. This calls read_history() in the underlying library.

readline.write_history_file([filename])

Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history. This calls write_history() in the underlying library.

readline.append_history_file(nelements[, filename])

Append the last nelements items of history to a file. The default filename is ~/.history. The file must already exist. This calls append_history() in the underlying library. This function only exists if Python was compiled for a version of the library that supports it.

Added in version 3.5.

readline.get_history_length()
readline.set_history_length(length)

履歴ファイルに保存する行数を設定または取得します。 write_history_file() 関数はこの値を使い、基盤となるライブラリの history_truncate_file() を呼び出して履歴ファイルを切り詰めます。 負の値を指定すると履歴ファイルのサイズは無制限になります。

履歴リスト

以下の関数はグローバルな履歴リストを操作します:

readline.clear_history()

現在の履歴を消去します。 基盤となるライブラリの clear_history() を呼び出します。 この Python 関数は、対応するバージョンのライブラリを使って Python をコンパイルした場合にのみ存在します。

readline.get_current_history_length()

履歴に現在ある項目の数を返します。 (get_history_length() は履歴ファイルに書かれる最大行数を返します。)

readline.get_history_item(index)

index にある履歴項目の現在の内容を返します。 項目のインデックスは 1 から始まります。 基盤となるライブラリの history_get() を呼び出します。

readline.remove_history_item(pos)

位置で指定した項目を履歴から削除します。 位置は 0 から数えます。 基盤となるライブラリの remove_history() を呼び出します。

readline.replace_history_item(pos, line)

位置で指定した履歴項目を line に置き換えます。 位置は 0 から数えます。 基盤となるライブラリの replace_history_entry() を呼び出します。

readline.add_history(line)

line を最後に入力した行であるかのように履歴バッファに追加します。 基盤となるライブラリの add_history() を呼び出します。

readline.set_auto_history(enabled)

readline で入力を読み取る際に add_history() を自動的に呼び出す機能を有効または無効にします。 enabled 引数には真偽値を指定し、真なら履歴の自動追加が有効に、偽なら無効になります。

Added in version 3.6.

履歴の自動追加はデフォルトで有効です。 この設定の変更は次のセッションには引き継がれません。

開始フック

readline.set_startup_hook([function])

基盤となるライブラリの rl_startup_hook コールバックが呼び出す関数を設定または削除します。 function を指定すると新しいフック関数として使われます。 省略するか None を指定すると、設定済みの関数が削除されます。 フックは readline が最初のプロンプトを表示する直前に引数なしで呼び出されます。

readline.set_pre_input_hook([function])

基盤となるライブラリの rl_pre_input_hook コールバックが呼び出す関数を設定または削除します。 function を指定すると新しいフック関数として使われます。 省略するか None を指定すると、設定済みの関数が削除されます。 フックは最初のプロンプトを表示した後、readline が入力文字を読み取り始める直前に引数なしで呼び出されます。 この関数は、対応するバージョンのライブラリを使って Python をコンパイルした場合にのみ存在します。

補完

The following functions relate to implementing a custom word completion function. This is typically operated by the Tab key, and can suggest and automatically complete a word being typed. By default, Readline is set up to be used by rlcompleter to complete Python identifiers for the interactive interpreter. If the readline module is to be used with a custom completer, a different set of word delimiters should be set.

readline.set_completer([function])

completer 関数を設定または削除します。function が指定された場合、新たな completer 関数として用いられます; 省略された場合や None の場合、現在インストールされている completer 関数は削除されます。completer 関数は function(text, state) の形式で、関数が文字列でない値を返すまで state を 0, 1, 2, ..., にして呼び出します。この関数は text から始まる補完結果として次に来そうなものを返さなければなりません。

設定した補完関数は、基盤となるライブラリの rl_completion_matches() に渡される entry_func コールバックから呼び出されます。 text 文字列は、基盤となるライブラリの rl_attempted_completion_function コールバックに渡される最初の引数から取得します。

readline.get_completer()

completer 関数を取得します。completer 関数が設定されていなければ None を返します。

readline.get_completion_type()

実行しようとしている補完の種類を取得します。 基盤となるライブラリの rl_completion_type 変数の値を整数で返します。

readline.get_begidx()
readline.get_endidx()

補完範囲の開始または終了インデックスを取得します。 これらのインデックスは、基盤となるライブラリの rl_attempted_completion_function コールバックに渡される start 引数と end 引数です。 同じ入力編集操作でも、基盤となる C の readline 実装によって値が異なる場合があります。 例えば libedit は libreadline と異なる動作をすることが知られています。

readline.set_completer_delims(string)
readline.get_completer_delims()

補完で使う単語の区切り文字を設定または取得します。 区切り文字は補完対象の単語の開始位置 (補完範囲) を決めます。 これらの関数は基盤となるライブラリの rl_completer_word_break_characters 変数にアクセスします。

readline.set_completion_display_matches_hook([function])

補完候補を表示する関数を設定または削除します。 function を指定すると新しい補完候補表示関数として使われます。 省略するか None を指定すると、設定済みの関数が削除されます。 基盤となるライブラリの rl_completion_display_matches_hook コールバックを設定または解除します。 補完候補表示関数は候補を表示する必要があるたびに function(substitution, [matches], longest_match_length) の形で一度呼び出されます。

使用例

以下の例では、ユーザのホームディレクトリにある履歴ファイル .python_history の読み込みと保存を自動的に行うために、 readline モジュールの履歴の読み書き関数をどのように使うかを示しています。以下のソースコードは通常、対話セッション中はユーザの PYTHONSTARTUP ファイルから自動的に実行されます:

import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # デフォルトの履歴長は -1 (無制限) なので、履歴が際限なく増える場合がある
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)

Python が 対話モード で実行される時、このコードは実際には自動的に実行されます ( readline の設定 を参照してください)。

次の例では上記と同じ目的を達成できますが、ここでは新規の履歴のみを追加することで、並行して対話セッションがサポートされます:

import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")

try:
    readline.read_history_file(histfile)
    h_len = readline.get_current_history_length()
except FileNotFoundError:
    open(histfile, 'wb').close()
    h_len = 0

def save(prev_h_len, histfile):
    new_h_len = readline.get_current_history_length()
    readline.set_history_length(1000)
    readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)

次の例では code.InteractiveConsole クラスを拡張し、履歴の保存・復旧をサポートします。

import atexit
import code
import os
import readline

class HistoryConsole(code.InteractiveConsole):
    def __init__(self, locals=None, filename="<console>",
                 histfile=os.path.expanduser("~/.console-history")):
        code.InteractiveConsole.__init__(self, locals, filename)
        self.init_history(histfile)

    def init_history(self, histfile):
        readline.parse_and_bind("tab: complete")
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except FileNotFoundError:
                pass
            atexit.register(self.save_history, histfile)

    def save_history(self, histfile):
        readline.set_history_length(1000)
        readline.write_history_file(histfile)

注釈

The new REPL introduced in version 3.13 doesn't support readline. However, readline can still be used by setting the PYTHON_BASIC_REPL environment variable.