内容表

  • readline — GNU readline 接口
    • 初始文件
    • 行缓冲
    • 历史文件
    • 历史列表
    • 启动挂钩
    • 补全
    • 范例

上一话题

stringprep — 互联网字符串预备

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 文本处理服务
  9. readline — GNU readline 接口

readline — GNU readline 接口 ¶


The readline 模块定义了促进 Python 解释器补全和读取/写入历史文件的很多函数。可以直接使用此模块,或凭借 rlcompleter 模块,支持交互提示补全 Python 标识符。使用此模块做出的设置会影响解释器交互提示的行为和提供提示通过内置 input() 函数。

可以凭借初始化文件配置 readline 键绑定,通常 .inputrc 在您的 Home (主) 目录。见 readline 初始文件 在 GNU readline 手册了解该文件的格式和可允许构造的有关信息,及 readline 库的一般能力。

注意

可以实现底层 readline 库 API 通过 libedit 库而不是 GNU readline。在 macOS readline 模块检测运行时在使用哪个库。

配置文件对于 libedit 异于 GNU readline。若以编程方式加载配置字符串,可以校验文本 libedit 在 readline.__doc__ 以区分 GNU readline 和 libedit。

若使用 editline / libedit 在 macOS 仿真 readline,位于 Home (主) 目录的初始化文件名为 .editrc 。例如,以下内容在 ~/.editrc 将打开 vi 键绑定和 Tab 补全:

python:bind -v
python:bind ^I rl_complete
										

初始文件 ¶

下列函数涉及初始文件和用户配置:

readline. parse_and_bind ( string ) ¶

执行初始提供行按 string 自变量。这调用 rl_parse_and_bind() 在底层库中。

readline. read_init_file ( [ filename ] ) ¶

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

行缓冲 ¶

下列函数运转于行缓冲:

readline. get_line_buffer ( ) ¶

返回行缓冲的当前内容 ( rl_line_buffer 在底层库中)。

readline. insert_text ( string ) ¶

将文本插入光标位置行缓冲。这调用 rl_insert_text() 在底层库,但忽略返回值。

readline. redisplay ( ) ¶

改变在屏幕中显示什么,以反映行缓冲的当前内容。这调用 rl_redisplay() 在底层库中。

历史文件 ¶

下列函数运转于历史文件:

readline. read_history_file ( [ filename ] ) ¶

加载 readline 历史文件,并将其追加到历史列表。默认 filename 为 ~/.history 。这调用 read_history() 在底层库中。

readline. write_history_file ( [ filename ] ) ¶

Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history 。这调用 write_history() 在底层库中。

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

Set or return the desired number of lines to save in the history file. The write_history_file() function uses this value to truncate the history file, by calling history_truncate_file() in the underlying library. Negative values imply unlimited history file size.

历史列表 ¶

下列函数运转于全局历史列表:

readline. clear_history ( ) ¶

清零当前历史。这调用 clear_history() in the underlying library. The Python function only exists if Python was compiled for a version of the library that supports it.

readline. get_current_history_length ( ) ¶

Return the number of items currently in the history. (This is different from get_history_length() , which returns the maximum number of lines that will be written to a history file.)

readline. get_history_item ( index ) ¶

Return the current contents of history item at index 。项 index 基于 1。这调用 history_get() 在底层库中。

readline. remove_history_item ( pos ) ¶

Remove history item specified by its position from the history. The position is zero-based. This calls remove_history() 在底层库中。

readline. replace_history_item ( pos , line ) ¶

Replace history item specified by its position with line . The position is zero-based. This calls replace_history_entry() 在底层库中。

readline. add_history ( line ) ¶

追加 line 到历史缓冲,就像最后键入行。这调用 add_history() 在底层库中。

readline. set_auto_history ( enabled ) ¶

启用 (或禁用) 自动调用 add_history() 当读取输入凭借 readline。 被启用 argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history.

Added in version 3.6.

CPython 实现细节: Auto history is enabled by default, and changes to this do not persist across multiple sessions.

启动挂钩 ¶

readline. set_startup_hook ( [ function ] ) ¶

Set or remove the function invoked by the rl_startup_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None , any function already installed is removed. The hook is called with no arguments just before readline prints the first prompt.

readline. set_pre_input_hook ( [ function ] ) ¶

Set or remove the function invoked by the rl_pre_input_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None , any function already installed is removed. The hook is called with no arguments after the first prompt has been printed and just before readline starts reading input characters. This function only exists if Python was compiled for a version of the library that supports it.

补全 ¶

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 ] ) ¶

Set or remove the completer function. If function is specified, it will be used as the new completer function; if omitted or None , any completer function already installed is removed. The completer function is called as function(text, state) , for state in 0 , 1 , 2 , …, until it returns a non-string value. It should return the next possible completion starting with text .

The installed completer function is invoked by the entry_func callback passed to rl_completion_matches() in the underlying library. The text string comes from the first parameter to the rl_attempted_completion_function callback of the underlying library.

readline. get_completer ( ) ¶

获取补全器函数,或 None 若没有设置补全器函数。

readline. get_completion_type ( ) ¶

Get the type of completion being attempted. This returns the rl_completion_type variable in the underlying library as an integer.

readline. get_begidx ( ) ¶
readline. get_endidx ( ) ¶

Get the beginning or ending index of the completion scope. These indexes are the start and end arguments passed to the rl_attempted_completion_function callback of the underlying library. The values may be different in the same input editing scenario based on the underlying C readline implementation. Ex: libedit is known to behave differently than libreadline.

readline. set_completer_delims ( string ) ¶
readline. get_completer_delims ( ) ¶

Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the rl_completer_word_break_characters variable in the underlying library.

readline. set_completion_display_matches_hook ( [ function ] ) ¶

Set or remove the completion display function. If function is specified, it will be used as the new completion display function; if omitted or None , any completion display function already installed is removed. This sets or clears the rl_completion_display_matches_hook callback in the underlying library. The completion display function is called as function(substitution, [matches], longest_match_length) once each time matches need to be displayed.

范例 ¶

以下范例演示如何使用 readline 模块的历史读取和写入功能,以自动加载和保存历史文件命名 .python_history 从用户 Home (主) 目录。以下代码在交互式会话期间,通常会自动执行从用户的 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)
										

此代码实际会自动运行,当 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)
										

内容表

  • readline — GNU readline 接口
    • 初始文件
    • 行缓冲
    • 历史文件
    • 历史列表
    • 启动挂钩
    • 补全
    • 范例

上一话题

stringprep — 互联网字符串预备

下一话题

rlcompleter — 用于 GNU readline 的补全函数

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 文本处理服务
  9. readline — GNU readline 接口

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1