16.8. readline — GNU readline 界面

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

Note

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

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

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

16.8.1. 初始化文件

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

  • readline. parse_and_bind(* string *)

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

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

16.8.2. 行缓冲器

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

  • readline. get_line_buffer ( )

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

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

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

16.8.3. 历史 Files

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

  • readline. read_history_file([文件名])

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

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

  • readline. set_history_length(* length *)

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

16.8.4. 历史记录

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

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

2.4 版的新Function。

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

2.3 版的新Function。

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

2.3 版的新Function。

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

2.4 版的新Function。

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

2.4 版的新Function。

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

16.8.5. 启动钩

Note

2.3 版的新Function。

  • 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 是针对支持该库的版本编译的时,此函数才存在。

16.8.6. 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

2.3 版的新Function。

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

2.6 版的新Function。

  • 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)

2.6 版的新Function。

16.8.7. Example

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

import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(1000)
except IOError:
    pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile

以下示例扩展了code.InteractiveConsole类以支持历史记录保存/恢复。

import code
import readline
import atexit
import os

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 IOError:
                pass
            atexit.register(self.save_history, histfile)

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