readlineGNU readline interfaceGNU readline接口


The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. readline模块定义了许多函数,以便于完成和读取/写入Python解释器中的历史文件。This module can be used directly, or via the rlcompleter module, which supports completion of Python identifiers at the interactive prompt. 该模块可以直接使用,也可以通过rlcompleter模块使用,该模块支持在交互提示下完成Python标识符。Settings made using this module affect the behaviour of both the interpreter’s interactive prompt and the prompts offered by the built-in input() function.使用此模块进行的设置会影响解释器的交互提示和内置input()函数提供的提示的行为。

Readline keybindings may be configured via an initialization file, typically .inputrc in your home directory. Readline键绑定可以通过初始化文件进行配置,通常是主目录中的.inputrcSee Readline Init File in the GNU Readline manual for information about the format and allowable constructs of that file, and the capabilities of the Readline library in general.请参阅GNU Readline手册中的Readline Init文件,了解该文件的格式和允许的构造,以及Readline库的一般功能。

Note

The underlying Readline library API may be implemented by the libedit library instead of GNU readline. 底层Readline库API可以由libedit库而不是GNU Readline实现。On macOS the readline module detects which library is being used at run time.在macOS上,readline模块检测运行时正在使用的库。

The configuration file for libedit is different from that of GNU readline. libedit的配置文件不同于GNU readline的配置文件。If you programmatically load configuration strings you can check for the text “libedit” in readline.__doc__ to differentiate between GNU readline and libedit.如果以编程方式加载配置字符串,可以在readline.__doc__中检查文本“libedit”用于区分GNU readline和libedit。

If you use editline/libedit readline emulation on macOS, the initialization file located in your home directory is named .editrc. 如果在macOS上使用editline/libedit readline仿真,则位于主目录中的初始化文件名为.editrcFor example, the following content in ~/.editrc will turn ON vi keybindings and TAB completion:例如,~/.editrc中的以下内容将打开vi键绑定和制表符完成:

python:bind -v
python:bind ^I rl_complete

Init file初始化文件

The following functions relate to the init file and user configuration:以下功能与init文件和用户配置有关:

readline.parse_and_bind(string)

Execute the init line provided in the string argument. 执行string参数中提供的init行。This calls rl_parse_and_bind() in the underlying library.这将调用底层库中的rl_parse_and_bind()

readline.read_init_file([filename])

Execute a readline initialization file. 执行readline初始化文件。The default filename is the last filename used. 默认文件名是最后使用的文件名。This calls rl_read_init_file() in the underlying library.这将调用底层库中的rl_read_init_file()

Line buffer线路缓冲器

The following functions operate on the line buffer:以下功能在线路缓冲器上运行:

readline.get_line_buffer()

Return the current contents of the line buffer (rl_line_buffer in the underlying library).返回行缓冲区的当前内容(底层库中的rl_line_buffer)。

readline.insert_text(string)

Insert text into the line buffer at the cursor position. 在光标位置将文本插入行缓冲区。This calls rl_insert_text() in the underlying library, but ignores the return value.这将调用底层库中的rl_insert_text(),但忽略返回值。

readline.redisplay()

Change what’s displayed on the screen to reflect the current contents of the line buffer. 更改屏幕上显示的内容以反映行缓冲区的当前内容。This calls rl_redisplay() in the underlying library.这将调用底层库中的rl_redisplay()

History file历史记录文件

The following functions operate on a history file:以下函数对历史文件进行操作:

readline.read_history_file([filename])

Load a readline history file, and append it to the history list. 加载一个readline历史文件,并将其附加到历史列表中。The default filename is ~/.history. 默认文件名为~/.historyThis calls read_history() in the underlying library.这将调用底层库中的read_history()

readline.write_history_file([filename])

Save the history list to a readline history file, overwriting any existing file. 将历史列表保存到readline历史文件,覆盖任何现有文件。The default filename is ~/.history. 默认文件名为~/.historyThis calls write_history() in the underlying library.这将调用底层库中的write_history()

readline.append_history_file(nelements[, filename])

Append the last nelements items of history to a file. 将历史的最后一个nelements项附加到文件中。The default filename is ~/.history. 默认文件名为~/.historyThe file must already exist. 文件必须已存在。This calls append_history() in the underlying library. 这将调用底层库中的append_history()This function only exists if Python was compiled for a version of the library that supports it.只有为支持该函数的库版本编译Python时,该函数才存在。

New in version 3.5.版本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. write_history_file()函数通过调用基础库中的history_truncate_file()来使用此值截断历史文件。Negative values imply unlimited history file size.负值表示历史文件大小不受限制。

History list历史记录列表

The following functions operate on a global history list:以下功能在全局历史列表上运行:

readline.clear_history()

Clear the current history. 清除当前历史记录。This calls clear_history() in the underlying library. 这将调用底层库中的clear_history()The Python function only exists if Python was compiled for a version of the library that supports it.只有为支持Python的库版本编译Python时,Python函数才存在。

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.)(这与get_history_length()不同,后者返回将写入历史文件的最大行数。)

readline.get_history_item(index)

Return the current contents of history item at index. 返回index处历史项的当前内容。The item index is one-based. 项目索引基于一个。This calls history_get() in the underlying library.这将调用底层库中的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() in the underlying library.这将调用底层库中的remove_history()

readline.replace_history_item(pos, line)

Replace history item specified by its position with line. 将其位置指定的历史项替换为lineThe position is zero-based. 该位置以零为基础。This calls replace_history_entry() in the underlying library.这将调用基础库中的replace_history_entry()

readline.add_history(line)

Append line to the history buffer, as if it was the last line typed. line追加到历史缓冲区,就像它是最后键入的行一样。This calls add_history() in the underlying library.这将调用基础库中的add_history()

readline.set_auto_history(enabled)

Enable or disable automatic calls to add_history() when reading input via readline. 当通过readline读取输入时,启用或禁用自动调用add_history()The enabled argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history.enabled参数应该是一个布尔值,如果为true,则启用自动历史记录;如果为false,则禁用自动历史记录。

New in version 3.6.版本3.6中新增。

CPython implementation detail: Auto history is enabled by default, and changes to this do not persist across multiple sessions.CPython实现详细信息:默认情况下启用自动历史记录,对此的更改不会在多个会话中持续。

Startup hooks启动挂钩

readline.set_startup_hook([function])

Set or remove the function invoked by the rl_startup_hook callback of the underlying library. 设置或删除由底层库的rl_startup_hook回调调用的函数。If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. 如果指定了function,则将其用作新的钩子函数;如果省略或为None,则删除任何已安装的功能。The hook is called with no arguments just before readline prints the first prompt.在readline打印第一个提示之前,调用钩子时没有参数。

readline.set_pre_input_hook([function])

Set or remove the function invoked by the rl_pre_input_hook callback of the underlying library. 设置或删除由底层库的rl_pre_input_hook回调调用的函数。If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. 如果指定了function,则将其用作新的钩子函数;如果省略或为None,则删除任何已安装的功能。The hook is called with no arguments after the first prompt has been printed and just before readline starts reading input characters. 在打印第一个提示之后,readline开始读取输入字符之前,调用钩子时不带任何参数。This function only exists if Python was compiled for a version of the library that supports it.只有为支持该函数的库版本编译Python时,该函数才存在。

Completion完成

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. 这通常由Tab键操作,可以建议并自动完成键入的单词。By default, Readline is set up to be used by rlcompleter to complete Python identifiers for the interactive interpreter. 默认情况下,Readline设置为rlcompleter用于完成交互式解释器的Python标识符。If the readline module is to be used with a custom completer, a different set of word delimiters should be set.如果readline模块要与自定义完成符一起使用,则应设置一组不同的字分隔符。

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. 如果指定了function,则将其用作新的补足符函数;如果省略或为None,则删除已安装的任何补全函数。The completer function is called as function(text, state), for state in 0, 1, 2, …, until it returns a non-string value. 对于012…中的state,完成符函数被称为function(text, state),直到它返回非字符串值为止。It should return the next possible completion starting with text.它应该返回从text开始的下一个可能的完成。

The installed completer function is invoked by the entry_func callback passed to rl_completion_matches() in the underlying library. 已安装的completer函数由传递给基础库中rl_completion_matches()entry_func回调调用。The text string comes from the first parameter to the rl_attempted_completion_function callback of the underlying library.text字符串来自底层库的rl_attempted_completion_function回调的第一个参数。

readline.get_completer()

Get the completer function, or None if no completer function has been set.获得完成函数,如果未设置完成函数,则获得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.这会将基础库中的rl_completion_type变量作为整数返回。

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. 这些索引是传递给底层库的rl_attempted_completion_function回调的startend参数。The values may be different in the same input editing scenario based on the underlying C readline implementation. 在相同的输入编辑场景中,基于底层C readline实现,这些值可能不同。Ex: libedit is known to behave differently than libreadline.例如:众所周知,libedit的行为与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.这些函数访问基础库中的rl_completer_word_break_characters变量。

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. 如果指定了function,则将其用作新的完成显示功能;如果省略或None,则删除已安装的任何完成显示功能。This sets or clears the rl_completion_display_matches_hook callback in the underlying library. 这将设置或清除基础库中的rl_completion_display_matches_hook回调。The completion display function is called as function(substitution, [matches], longest_match_length) once each time matches need to be displayed.每次需要显示匹配项时,完成显示函数称为function(substitution, [matches], longest_match_length)

Example实例

The following example demonstrates how to use the readline module’s history reading and writing functions to automatically load and save a history file named .python_history from the user’s home directory. 下面的示例演示如何使用readline模块的历史读取和写入函数从用户的主目录中自动加载和保存名为.python_history的历史文件。The code below would normally be executed automatically during interactive sessions from the user’s PYTHONSTARTUP file.下面的代码通常会在交互会话期间从用户的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)

This code is actually automatically run when Python is run in interactive mode (see Readline configuration).当Python在交互模式下运行时,此代码实际上会自动运行(请参阅Readline配置)。

The following example achieves the same goal but supports concurrent interactive sessions, by only appending the new history.下面的示例实现了相同的目标,但只通过附加新的历史记录来支持并发交互会话。

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)

The following example extends the code.InteractiveConsole class to support history save/restore.下面的示例扩展了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)