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与初始化文件和用户配置有关:

16.8.2. 行缓冲器

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

16.8.3. 历史 Files

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

16.8.4. 历史记录

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

2.4 版的新Function。

2.3 版的新Function。

2.3 版的新Function。

2.4 版的新Function。

2.4 版的新Function。

16.8.5. 启动钩

Note

2.3 版的新Function。

16.8.6. Completion

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

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

2.3 版的新Function。

2.6 版的新Function。

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)
首页