readline — GNU readline 인터페이스¶
The readline module defines a number of functions to facilitate
completion and reading/writing of history files from the Python interpreter.
This module can be used directly, or via the rlcompleter module, which
supports completion of Python identifiers at the interactive prompt. 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.
Readline 키 바인딩은 초기화 파일을 통해 구성할 수 있습니다, 일반적으로 홈 디렉터리의 .inputrc. 이 파일의 형식과 허용되는 구성 및 Readline 라이브러리의 기능에 대한 일반적인 정보는 GNU Readline 매뉴얼의 Readline Init File을 참조하십시오.
This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see Requirements for optional modules.
참고
The underlying Readline library API may be implemented by
the editline (libedit) library instead of GNU readline.
On macOS the readline module detects which library is being used
at run time.
editline의 구성 파일은 GNU readline의 구성 파일과 다릅니다. 프로그래밍 방식으로 구성 문자열을 로드하는 경우 어떤 라이브러리가 사용되고 있는지 backend를 사용하여 확인할 수 있습니다.
macOS에서 editline/libedit readline 에뮬레이션을 사용하는 경우, 홈 디렉터리에 있는 초기화 파일의 이름은 .editrc입니다. 예를 들어, ~/.editrc의 다음 내용은 vi 키 바인딩과 TAB 완성을 켭니다:
python:bind -v
python:bind ^I rl_complete
Also note that different libraries may use different history file formats. When switching the underlying library, existing history files may become unusable.
- readline.backend¶
The name of the underlying Readline library being used, either
"readline"or"editline".Added in version 3.13.
초기화 파일¶
다음 함수는 초기화 파일 및 사용자 구성과 관련이 있습니다:
- readline.parse_and_bind(string)¶
string 인자에 제공된 초기화 줄을 실행합니다. 하부 라이브러리에서
rl_parse_and_bind()를 호출합니다.
- readline.read_init_file([filename])¶
Execute a readline initialization file. The default filename is the last filename used. This calls
rl_read_init_file()in the underlying library. It raises an auditing eventopenwith the file name if given, and"<readline_init_file>"otherwise, regardless of which file the library resolves.버전 3.14에서 변경: The auditing event was added.
줄 버퍼¶
다음 함수는 라인 버퍼에 대해 작용합니다:
- readline.get_line_buffer()¶
줄 버퍼의 현재 내용(하부 라이브러리의
rl_line_buffer)을 반환합니다.
- readline.insert_text(string)¶
줄 버퍼의 커서 위치에 텍스트를 삽입합니다. 하부 라이브러리에서
rl_insert_text()를 호출하지만, 반환 값은 무시합니다.
- readline.redisplay()¶
줄 버퍼의 현재 내용을 반영하도록 화면에 표시되는 내용을 변경합니다. 하부 라이브러리에서
rl_redisplay()를 호출합니다.
히스토리 파일¶
다음 함수는 히스토리 파일에 대해 작용합니다:
- 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 and raises an auditing eventopenwith the file name if given and"~/.history"otherwise.버전 3.14에서 변경: The auditing event was added.
- readline.write_history_file([filename])¶
Save the history list to a readline history file, overwriting any existing file. The default filename is
~/.history. This callswrite_history()in the underlying library and raises an auditing eventopenwith the file name if given and"~/.history"otherwise.버전 3.14에서 변경: The auditing event was added.
- 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 callsappend_history()in the underlying library. This function only exists if Python was compiled for a version of the library that supports it. It raises an auditing eventopenwith the file name if given and"~/.history"otherwise.Added in version 3.5.
버전 3.14에서 변경: The auditing event was added.
- readline.get_history_length()¶
- readline.set_history_length(length)¶
히스토리 파일에 저장하기 원하는 줄 수를 설정하거나 반환합니다.
write_history_file()함수는 이 값을 사용하여, 하부 라이브러리에서history_truncate_file()을 호출하여 히스토리 파일을 자릅니다. 음수 값은 제한 없는 히스토리 파일 크기를 의미합니다.
히스토리 목록¶
다음 함수는 전역 히스토리 목록에 대해 작용합니다:
- readline.clear_history()¶
현재 히스토리를 지웁니다. 하부 라이브러리에서
clear_history()를 호출합니다. 파이썬 함수는 파이썬이 이를 지원하는 라이브러리 버전으로 컴파일된 경우에만 존재합니다.
- readline.get_current_history_length()¶
현재 히스토리에 있는 항목 수를 반환합니다. (이것은 히스토리 파일에 기록될 최대 줄 수를 반환하는
get_history_length()와 다릅니다.)
- readline.get_history_item(index)¶
index에 있는 히스토리 항목의 현재 내용을 반환합니다. 항목 인덱스는 1부터 시작합니다. 하부 라이브러리에서
history_get()을 호출합니다.
- readline.remove_history_item(pos)¶
히스토리에서 위치(pos)로 지정된 히스토리 항목을 제거합니다. 위치는 0부터 시작합니다. 하부 라이브러리에서
remove_history()를 호출합니다.
- readline.replace_history_item(pos, line)¶
위치(pos)로 지정된 히스토리 항목을 line으로 교체합니다. 위치는 0부터 시작합니다. 하부 라이브러리에서
replace_history_entry()를 호출합니다.
- readline.add_history(line)¶
마지막 줄이 입력된 것처럼 히스토리 버퍼에 line을 추가합니다. 하부 라이브러리에서
add_history()를 호출합니다.
- readline.set_auto_history(enabled)¶
readline을 통해 입력을 읽을 때
add_history()에 대한 자동 호출을 활성화 또는 비활성화합니다. enabled 인자는 참일 때 자동 히스토리를 활성화하고, 거짓일 때 자동 기록을 비활성화하는 불리언 값이어야 합니다.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])¶
하부 라이브러리의
rl_startup_hook콜백에 의해 호출되는 함수를 설정하거나 제거합니다. function이 지정되면 새 훅(hook) 함수로 사용됩니다; 생략되거나None이면, 이미 설치된 함수가 제거됩니다. 이 훅은 readline이 첫 번째 프롬프트를 인쇄하기 직전에 인자 없이 호출됩니다.
- readline.set_pre_input_hook([function])¶
하부 라이브러리의
rl_pre_input_hook콜백에 의해 호출되는 함수를 설정하거나 제거합니다. function이 지정되면, 새 훅 함수로 사용됩니다; 생략되거나None이면, 이미 설치된 함수가 제거됩니다. 이 훅은 첫 번째 프롬프트가 인쇄된 후 readline이 입력 문자를 읽기 시작하기 직전에 인자 없이 호출됩니다. 이 함수는 파이썬이 이를 지원하는 라이브러리 버전으로 컴파일된 경우에만 존재합니다.
- readline.get_pre_input_hook()¶
Get the current pre-input hook function, or
Noneif no pre-input hook function has been set. This function only exists if Python was compiled for a version of the library that supports it.Added in version 3.15.
완성¶
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])¶
완성 함수를 설정하거나 제거합니다. function이 지정되면 새 완성 함수로 사용됩니다; 생략하거나
None이면, 이미 설치된 완성 함수가 제거됩니다. 완성 함수는 문자열이 아닌 값을 반환할 때까지0,1,2등의 state에 대해function(text, state)로 호출됩니다. text로 시작하는 다음으로 가능한 완성을 반환해야 합니다.설치된 완성 함수는 하부 라이브러리의
rl_completion_matches()로 전달된 entry_func 콜백에 의해 호출됩니다. text 문자열은 하부 라이브러리의rl_attempted_completion_function콜백의 첫 번째 매개 변수로부터 옵니다.
- readline.get_completer()¶
완성 함수나, 완성 함수가 설정되지 않았으면
None을 얻습니다.
- readline.get_completion_type()¶
시도 중인 완성 유형을 가져옵니다. 하부 라이브러리의
rl_completion_type변수를 정수로 반환합니다.
- readline.get_begidx()¶
- readline.get_endidx()¶
완성 범위(completion scope)의 시작이나 끝 인덱스를 가져옵니다. 이 인덱스는 하부 라이브러리의
rl_attempted_completion_function콜백에 전달된 start와 end 인자입니다. 같은 입력 편집 시나리오에서 하부 C readline 구현에 따라 값이 다를 수 있습니다. 예: libedit는 libreadline과 다르게 동작하는 것으로 알려져 있습니다.
- readline.set_completer_delims(string)¶
- readline.get_completer_delims()¶
완성을 위한 단어 구분자를 설정하거나 가져옵니다. 이것들은 완성을 위해 고려할 단어의 시작(완성 범위)을 결정합니다. 이 함수는 하부 라이브러리의
rl_completer_word_break_characters변수를 액세스합니다.
- readline.set_completion_display_matches_hook([function])¶
완성 표시 함수를 설정하거나 제거합니다. function이 지정되면, 새로운 완성 표시 함수로 사용됩니다; 생략하거나
None이면, 이미 설치된 완성 표시 함수가 제거됩니다. 하부 라이브러리에서rl_completion_display_matches_hook콜백을 설정하거나 지웁니다. 완성 표시 함수는 일치를 표시해야 할 때마다 한 번function(substitution, [matches], longest_match_length)로 호출됩니다.
예제¶
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. The code
below would normally be executed automatically during interactive sessions
from the user’s PYTHONSTARTUP file.
import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
readline.read_history_file(histfile)
# 기본 히스토리 길이는 -1(무한)이며, 제약 없이 커질 수 있습니다
readline.set_history_length(1000)
except FileNotFoundError:
pass
atexit.register(readline.write_history_file, histfile)
이 코드는 실제로 파이썬이 대화형 모드로 실행될 때 자동으로 실행됩니다 (Readline 구성을 참조하십시오).
다음 예는 같은 목표를 달성하지만 새 히스토리를 덧붙이기만 해서 동시적인(concurrent) 대화형 세션을 지원합니다.
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)
참고
The new REPL introduced in version 3.13 doesn’t support readline.
However, readline can still be used by setting the PYTHON_BASIC_REPL
environment variable.