readline — Interface para o GNU readline


O módulo readline define uma série de funções para facilitar o autocomplemento e leitura/gravação de arquivos históricos do interpretador Python. Este módulo pode ser usado diretamente ou através do módulo rlcompleter, que provê o autocomplemento de identificadores Python no prompt interativo. As configurações feitas usando este módulo afetam o comportamento do prompt interativo do interpretador e dos prompts oferecidos pela função embutida input().

As combinações de teclas do Readline podem ser configuradas através de um arquivo de inicialização, normalmente .inputrc em seu diretório inicial. Consulte Readline Init File no manual do GNU Readline para obter informações sobre o formato e construções permitidas desse arquivo e os recursos da biblioteca do Readline em geral.

Disponibilidade: not Android, not iOS, not WASI.

Este módulo não tem suporte em plataformas móveis ou plataformas WebAssembly.

Nota

A API da biblioteca subjacente do Readline pode ser implementada pela biblioteca editline (libedit) em vez do GNU readline. No macOS, o módulo readline detecta qual biblioteca está sendo usada em tempo de execução.

O arquivo de configuração do editline é diferente daquele do GNU readline. Se você carregar strings de configuração programaticamente, você pode usar backend para determinar qual biblioteca está sendo usada.

Se você usar a emulação de readline do editline/libedit no macOS, o arquivo de inicialização localizado em seu diretório inicial será denominado .editrc. Por exemplo, o seguinte conteúdo em ~/.editrc ativará os atalhos de teclado vi e o autocomplemento de TAB:

python:bind -v
python:bind ^I rl_complete

Observe também que bibliotecas diferentes podem usar formatos de arquivo de histórico diferentes. Ao alternar a biblioteca subjacente, os arquivos de histórico existentes podem se tornar inutilizáveis.

readline.backend

O nome da biblioteca Readline subjacente que está sendo usada, seja "readline" ou "editline".

Adicionado na versão 3.13.

Arquivo init

As seguintes funções estão relacionadas ao arquivo init e à configuração do usuário:

readline.parse_and_bind(string)

Execute the init line provided in the string 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 filename used. This calls rl_read_init_file() in the underlying library.

Buffer de linha

As seguintes funções operam no buffer de linha:

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 ignores the return value.

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.

Arquivo de histórico

As seguintes funções operam em um arquivo histórico:

readline.read_history_file([filename])

Load a readline history file, and append it to the history list. The default filename is ~/.history. This calls read_history() in the underlying library.

readline.write_history_file([filename])

Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history. This calls write_history() in the underlying library.

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.

Adicionado na versão 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.

Lista de histórico

As seguintes funções operam em uma lista de histórico global:

readline.clear_history()

Clear the current history. This calls 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()

Retorna o número de itens atualmente no histórico. (Isso é diferente de get_history_length(), que retorna o número máximo de linhas que serão gravadas em um arquivo de histórico.)

readline.get_history_item(index)

Return the current contents of history item at index. The item index is 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() in the underlying library.

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() in the underlying library.

readline.add_history(line)

Append line 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 reading input via readline. The enabled argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history.

Adicionado na versão 3.6.

O histórico automático está ativado por padrão e as alterações não persistem em várias sessões.

Ganchos de inicialização

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.

Autocomplemento

As funções a seguir estão relacionadas à implementação de uma função personalizada de autocomplemento ou completion, em inglês, de palavras. Isso normalmente é operado pela tecla Tab e pode sugerir e completar automaticamente uma palavra que está sendo digitada. Por padrão, Readline está configurado para ser usado por rlcompleter para completar identificadores Python para o interpretador interativo. Se o módulo readline for usado com um autocomplemento personalizado, um conjunto diferente de delimitadores de palavras deverá ser definido.

readline.set_completer([function])

Define ou remove a função de autocomplemento. Se function for especificada, ela será usada como a nova função de autocomplemento; se omitido ou None, qualquer função de autocomplemento já instalada será removida. A função de autocomplemento é chamada como function(text, state), para state em 0, 1, 2, …, até retornar um valor que não seja string. Deve retornar o próximo autocomplemento possível começando com 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()

Obtém a função de autocomplemento ou None se nenhuma função de autocomplemento tiver sido definida.

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.

Exemplo

O exemplo a seguir demonstra como usar as funções de leitura e gravação de histórico do módulo readline para carregar e salvar automaticamente um arquivo de histórico chamado .python_history do diretório inicial do usuário. O código abaixo normalmente seria executado automaticamente durante sessões interativas do arquivo PYTHONSTARTUP do usuário.

import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # comprimento padrão do histórico é -1 (infinito), que pode crescer sem controle
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)

Na verdade, este código é executado automaticamente quando o Python é executado no modo interativo (veja Configuração Readline).

O exemplo a seguir atinge o mesmo objetivo, mas oferece suporte a sessões interativas simultâneas, anexando apenas o novo histórico.

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)

O exemplo a seguir estende a classe code.InteractiveConsole para prover salvamento/restauração do histórico.

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)