readline
--- GNU readline 介面¶
Thereadline
module defines a number of functions to facilitatecompletion and reading/writing of history files from the Python interpreter.This module can be used directly, or via therlcompleter
module, whichsupports completion of Python identifiers at the interactive prompt. Settingsmade using this module affect the behaviour of both the interpreter'sinteractive prompt and the prompts offered by the built-ininput()
function.
Readline keybindings may be configured via an initialization file, typically.inputrc
in your home directory. SeeReadline Init Filein the GNU Readline manual for information about the format andallowable constructs of that file, and the capabilities of theReadline library in general.
適用: not Android, not iOS, not WASI.
此模組在行動平台或WebAssembly 平台上不支援。
備註
The underlying Readline library API may be implemented bytheeditline
(libedit
) library instead of GNU readline.On macOS thereadline
module detects which library is being usedat run time.
The configuration file foreditline
is different from thatof GNU readline. If you programmatically load configuration stringsyou can usebackend
to determine which library is being used.
If you useeditline
/libedit
readline emulation on macOS, theinitialization file located in your home directory is named.editrc
. For example, the following content in~/.editrc
willturn ONvi keybindings and TAB completion:
python:bind-vpython:bind^Irl_complete
Also note that different libraries may use different history file formats.When switching the underlying library, existing history files may becomeunusable.
- readline.backend¶
The name of the underlying Readline library being used, either
"readline"
or"editline"
.在 3.13 版被加入.
Init file¶
The following functions relate to the init file and user configuration:
- readline.parse_and_bind(string)¶
Execute the init line provided in thestring argument. This calls
rl_parse_and_bind()
in the underlying library.
- readline.read_init_file([filename])¶
Execute a readline initialization file. The default filename is the last filenameused. This calls
rl_read_init_file()
in the underlying library.
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).
- readline.insert_text(string)¶
Insert text into the line buffer at the cursor position. This calls
rl_insert_text()
in the underlying library, but ignoresthe return value.
- readline.redisplay()¶
Change what's displayed on the screen to reflect the current contents of theline buffer. This calls
rl_redisplay()
in the underlying library.
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.The default filename is
~/.history
. This callsread_history()
in the underlying library.
- readline.write_history_file([filename])¶
Save the history list to a readline history file, overwriting anyexisting file. The default filename is
~/.history
. This callswrite_history()
in the underlying library.
- readline.append_history_file(nelements[,filename])¶
Append the lastnelements items of history to a file. The default filename is
~/.history
. The file must already exist. This callsappend_history()
in the underlying library. This functiononly exists if Python was compiled for a version of the librarythat supports it.在 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 truncatethe history file, by callinghistory_truncate_file()
inthe underlying library. Negative values implyunlimited 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 theunderlying library. The Python function only exists if Python wascompiled 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 willbe written to a history file.)
- readline.get_history_item(index)¶
Return the current contents of history item atindex. The item indexis one-based. This calls
history_get()
in the underlying library.
- readline.remove_history_item(pos)¶
Remove history item specified by its position from the history.The position is zero-based. This calls
remove_history()
inthe underlying library.
- readline.replace_history_item(pos,line)¶
Replace history item specified by its position withline.The position is zero-based. This calls
replace_history_entry()
in the underlying library.
- readline.add_history(line)¶
Appendline to the history buffer, as if it was the last line typed.This calls
add_history()
in the underlying library.
- readline.set_auto_history(enabled)¶
Enable or disable automatic calls to
add_history()
when readinginput via readline. Theenabled argument should be a Boolean valuethat when true, enables auto history, and that when false, disablesauto history.在 3.6 版被加入.
CPython 實作細節: Auto history is enabled by default, and changes to this do not persistacross multiple sessions.
Startup hooks¶
- readline.set_startup_hook([function])¶
Set or remove the function invoked by the
rl_startup_hook
callback of the underlying library. Iffunction is specified, it willbe used as the new hook function; if omitted orNone
, any functionalready installed is removed. The hook is called with noarguments 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. Iffunction is specified, it willbe used as the new hook function; if omitted orNone
, anyfunction already installed is removed. The hook is calledwith no arguments after the first prompt has been printed and just beforereadline starts reading input characters. This function only existsif Python was compiled for a version of the library that supports it.
Completion¶
The following functions relate to implementing a custom word completionfunction. This is typically operated by the Tab key, and can suggest andautomatically complete a word being typed. By default, Readline is set upto be used byrlcompleter
to complete Python identifiers forthe interactive interpreter. If thereadline
module is to be usedwith a custom completer, a different set of word delimiters should be set.
- readline.set_completer([function])¶
Set or remove the completer function. Iffunction is specified, it will beused as the new completer function; if omitted or
None
, any completerfunction already installed is removed. The completer function is called asfunction(text,state)
, forstate in0
,1
,2
, ..., until itreturns a non-string value. It should return the next possible completionstarting withtext.The installed completer function is invoked by theentry_func callbackpassed to
rl_completion_matches()
in the underlying library.Thetext string comes from the first parameter to therl_attempted_completion_function
callback of theunderlying library.
- readline.get_completer()¶
Get the completer function, or
None
if no completer function has been set.
- readline.get_completion_type()¶
Get the type of completion being attempted. This returns the
rl_completion_type
variable in the underlying library asan integer.
- readline.get_begidx()¶
- readline.get_endidx()¶
Get the beginning or ending index of the completion scope.These indexes are thestart andend arguments passed to the
rl_attempted_completion_function
callback of theunderlying library. The values may be different in the sameinput 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 thestart 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. Iffunction isspecified, it will be used as the new completion display function;if omitted or
None
, any completion display function alreadyinstalled is removed. This sets or clears therl_completion_display_matches_hook
callback in theunderlying library. The completion display function is called asfunction(substitution,[matches],longest_match_length)
onceeach time matches need to be displayed.
範例¶
The following example demonstrates how to use thereadline
module'shistory reading and writing functions to automatically load and save a historyfile named.python_history
from the user's home directory. The codebelow would normally be executed automatically during interactive sessionsfrom the user'sPYTHONSTARTUP
file.
importatexitimportosimportreadlinehistfile=os.path.join(os.path.expanduser("~"),".python_history")try:readline.read_history_file(histfile)# default history len is -1 (infinite), which may grow unrulyreadline.set_history_length(1000)exceptFileNotFoundError:passatexit.register(readline.write_history_file,histfile)
This code is actually automatically run when Python is run ininteractive mode (seeReadline configuration).
The following example achieves the same goal but supports concurrent interactivesessions, by only appending the new history.
importatexitimportosimportreadlinehistfile=os.path.join(os.path.expanduser("~"),".python_history")try:readline.read_history_file(histfile)h_len=readline.get_current_history_length()exceptFileNotFoundError:open(histfile,'wb').close()h_len=0defsave(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 thecode.InteractiveConsole
class tosupport history save/restore.
importatexitimportcodeimportosimportreadlineclassHistoryConsole(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)definit_history(self,histfile):readline.parse_and_bind("tab: complete")ifhasattr(readline,"read_history_file"):try:readline.read_history_file(histfile)exceptFileNotFoundError:passatexit.register(self.save_history,histfile)defsave_history(self,histfile):readline.set_history_length(1000)readline.write_history_file(histfile)