readline — GNU readline 接口


readline模块定义了许多Function,以促进从 Python 解释器完成和读取/写入历史文件。此模块可以直接使用,也可以passrlcompleter模块使用,该模块支持在交互式提示符下完成 Python 标识符。使用此模块进行的设置会影响解释程序的交互式提示和内置input()Function提供的提示的行为。

可以pass初始化文件(通常是主目录中的.inputrc)配置 Readline 键盘绑定。有关该文件的格式和允许的结构以及 Readline 库的Function的一般信息,请参见 GNU Readline 手册中的Readline 初始化文件

Note

底层的 Readline 库 API 可以由libedit库而不是 GNU readline 实现。在 macOS 上,readline模块在运行时检测正在使用哪个库。

libedit的配置文件与 GNU readline 的配置文件不同。如果您以编程方式加载配置字符串,则可以在readline.__doc__中检查文本“ libedit”以区分 GNU readline 和 libedit。

如果在 macOS 上使用* editline /libedit readline 仿真,则位于主目录中的初始化文件名为.editrc。例如,~/.editrc中的以下内容将打开 vi *键绑定和 TAB 完成:

python:bind -v
python:bind ^I rl_complete

Init file

以下Function与初始化文件和用户配置有关:

  • readline. parse_and_bind(* string *)

    • 执行* string *参数中提供的 init 行。这将在基础库中调用rl_parse_and_bind()
  • readline. read_init_file([文件名])

    • 执行 readline 初始化文件。默认文件名是最后使用的文件名。这将在基础库中调用rl_read_init_file()

Line buffer

以下Function在行缓冲区上运行:

  • readline. get_line_buffer ( )

    • 返回行缓冲区的当前内容(基础库中的rl_line_buffer)。
  • readline. insert_text(* string *)

    • 将文本插入到光标位置的行缓冲区中。这将在基础库中调用rl_insert_text(),但忽略返回值。
  • readline. redisplay ( )

    • 更改屏幕上显示的内容以反映行缓冲区的当前内容。这将在基础库中调用rl_redisplay()

History file

以下Function对历史文件起作用:

  • readline. read_history_file([文件名])

    • 加载 readline 历史记录文件,并将其附加到历史记录列表中。默认文件名是~/.history。这会在基础库中调用read_history()
  • readline. write_history_file([文件名])

    • 将历史记录列表保存到 readline 历史记录文件中,覆盖所有现有文件。默认文件名是~/.history。这会在基础库中调用write_history()
  • readline. append_history_file(元素 [,文件名])

    • 将历史记录的最后元素项追加到文件中。默认文件名是~/.history。该文件必须已经存在。这会在基础库中调用append_history()。仅当 Python 是针对支持该库的版本编译的时,此函数才存在。

3.5 版中的新Function。

  • readline. get_history_length ( )
  • readline. set_history_length(* length *)
    • 设置或返回所需的行数以保存在历史文件中。 write_history_file()函数pass在基础库中调用history_truncate_file()来使用此值截断历史文件。负值表示历史文件大小不受限制。

History list

以下Function对全局历史记录列表起作用:

  • readline. clear_history ( )

    • 清除当前历史记录。这将在基础库中调用clear_history()。仅当 Python 是针对支持该库的版本编译的,Python 函数才存在。
  • readline. get_current_history_length ( )

    • 返回历史 Logging 当前的项目数。 (这不同于get_history_length(),后者返回将写入历史文件的最大行数。)
  • readline. get_history_item(* index *)

    • 返回历史项目的当前内容,位于* index *。项目索引是基于一的。这将在基础库中调用history_get()
  • readline. remove_history_item(* pos *)

    • 从历史 Logging 删除由其位置指定的历史记录项目。该位置从零开始。这将在基础库中调用remove_history()
  • readline. replace_history_item(* pos line *)

    • 将其位置指定的历史记录项替换为* line *。该位置从零开始。这将在基础库中调用replace_history_entry()
  • readline. add_history(* line *)

    • 将* line *追加到历史记录缓冲区中,就像它是最后键入的行一样。这将在基础库中调用add_history()
  • readline. set_auto_history(启用)

    • pass readline 读取 Importing 时,启用或禁用对add_history()的自动调用。 * enabled *参数应该是一个布尔值,当为 true 时,启用自动历史记录;为 false 时,禁用自动历史记录。

3.6 版的新Function。

CPython 实现细节: 默认情况下,自动历史记录处于启用状态,对此更改的更改不会在多个会话中持续存在。

Startup hooks

  • readline. set_startup_hook([* function *])

    • 设置或删除基础库的rl_startup_hook回调调用的函数。如果指定了* function *,它将用作新的钩子函数;如果Ellipsis或None,则将删除所有已安装的Function。在 readline 打印第一个提示之前,将不带任何参数地调用该钩子。
  • readline. set_pre_input_hook([* function *])

    • 设置或删除基础库的rl_pre_input_hook回调调用的函数。如果指定了* function *,它将用作新的钩子函数;如果Ellipsis或None,则将删除所有已安装的Function。在第一个提示被打印之后,就在 readline 开始读取 Importing 字符之前,不带任何参数调用该钩子。仅当 Python 是针对支持该库的版本编译的时,此函数才存在。

Completion

以下Function与实现自定义单词完成Function有关。这通常由 Tab 键操作,可以建议并自动完成键入的单词。默认情况下,Readline 设置为供rlcompleter使用,以完成交互式解释器的 Python 标识符。如果readline模块要与自定义完成程序一起使用,则应设置不同的单词定界符集。

  • readline. set_completer([* function *])
    • 设置或删除完成器Function。如果指定了* function ,它将用作新的完成函数;如果Ellipsis或None,则将删除任何已安装的完成器Function。对于012,...中的 state ,该完成函数称为function(text, state),直到返回非字符串值。它应该返回以 text *开头的下一个可能的完成。

已安装的 completer 函数由传递给基础库中rl_completion_matches()的* entry_func *回调调用。 * text *字符串来自基础库的第一个参数到rl_attempted_completion_function回调。

  • readline. get_completer ( )

    • 获取完成Function,如果未设置完成Function,则返回None
  • readline. get_completion_type ( )

    • 获取try完成的类型。这将以整数形式返回基础库中的rl_completion_type变量。
  • readline. get_begidx ( )

  • readline. get_endidx ( )

    • 获取完成范围的开始或结束索引。这些索引是传递给基础库的rl_attempted_completion_function回调的* start end *参数。
  • readline. set_completer_delims(* string *)

  • readline. get_completer_delims ( )

    • 设置或获取单词定界符以完成。这些决定了要考虑完成的单词的开头(完成范围)。这些函数访问基础库中的rl_completer_word_break_characters变量。
  • readline. set_completion_display_matches_hook([* function *])

    • 设置或删除完成显示Function。如果指定了* function *,它将用作新的完成显示Function;如果Ellipsis或None,则将删除任何已安装的完成显示Function。这将设置或清除基础库中的rl_completion_display_matches_hook回调。每次需要显示匹配项时,完成显示Function就称为function(substitution, [matches], longest_match_length)

Example

下面的示例演示了如何使用readline模块的历史记录读取和写入Function从用户的主目录自动加载和保存名为.python_history的历史记录文件。以下代码通常在用户的 PYTHONSTARTUP文件的交互式会话期间自动执行。

import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)

当在interactive mode(请参阅Readline configuration)中运行 Python 时,此代码实际上会自动运行。

下面的示例pass添加新的历史记录,实现了相同的目标,但支持并发的交互式会话。

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)