Содержание страницы
13. Интерактивное редактирование ввода и подстановка из истории¶Interactive Input Editing and History Substitution
Некоторые версии интерпретатора Python поддерживают редактирование текущей строки ввода и подстановку из истории, аналогично тому, что есть в оболочках Korn и GNU Bash. Это реализовано с помощью библиотеки GNU Readline, которая поддерживает редактирование в стиле Emacs и vi. У этой библиотеки есть собственная документация, которую я здесь не буду повторять; однако основные принципы легко объяснить. Описанные здесь интерактивное редактирование и подстановка из истории опционально доступны в версиях интерпретатора для Unix и Cygwin.
В этой главе не описываются средства редактирования пакета PythonWin Марка Хаммонда или среды IDLE на основе Tk, распространяемой вместе с Python. Вызов истории командной строки, работающий в окнах DOS на NT и некоторых других версиях DOS и Windows, – это совсем другое дело.
13.1. Редактирование строки¶Line Editing
If supported, input line editing is active whenever the interpreter prints a primary or secondary prompt. The current line can be edited using the conventional Emacs control characters. The most important of these are: C-A (Control-A) moves the cursor to the beginning of the line, C-E to the end, C-B moves it one position to the left, C-F to the right. Backspace erases the character to the left of the cursor, C-D the character to its right. C-K kills (erases) the rest of the line to the right of the cursor, C-Y yanks back the last killed string. C-underscore undoes the last change you made; it can be repeated for cumulative effect.
13.2. Подстановка из истории¶History Substitution
History substitution works as follows. All non-empty input lines issued are saved in a history buffer, and when a new prompt is given you are positioned on a new line at the bottom of this buffer. C-P moves one line up (back) in the history buffer, C-N moves one down. Any line in the history buffer can be edited; an asterisk appears in front of the prompt to mark a line as modified. Pressing the Return key passes the current line to the interpreter. C-R starts an incremental reverse search; C-S starts a forward search.
13.3. Привязки клавиш¶Key Bindings
The key bindings and some other parameters of the Readline library can be customized by placing commands in an initialization file called ~/.inputrc. Key bindings have the form
key-name: function-name
или
"string": function-name
а параметры можно задать с помощью
set option-name value
Например:
# Я предпочитаю редактирование в стиле vi:
set editing-mode vi
# Редактирование одной строкой:
set horizontal-scroll-mode On
# Переназначить некоторые клавиши:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
Note that the default binding for Tab in Python is to insert a Tab character instead of Readline’s default filename completion function. If you insist, you can override this by putting
Tab: complete
in your ~/.inputrc. (Of course, this makes it harder to type indented continuation lines if you’re accustomed to using Tab for that purpose.)
Автоматическое дополнение имён переменных и модулей опционально доступно. Чтобы включить его в интерактивном режиме интерпретатора, добавьте следующее в ваш файл запуска: [1]
import rlcompleter, readline
readline.parse_and_bind('tab: complete')
This binds the Tab key to the completion function, so hitting the Tab key twice suggests completions; it looks at Python statement names, the current local variables, and the available module names. For dotted expressions such as string.a, it will evaluate the expression up to the final '.' and then suggest completions from the attributes of the resulting object. Note that this may execute application-defined code if an object with a __getattr__() method is part of the expression.
A more capable startup file might look like this example. Note that this deletes the names it creates once they are no longer needed; this is done since the startup file is executed in the same namespace as the interactive commands, and removing the names avoids creating side effects in the interactive environment. You may find it convenient to keep some of the imported modules, such as os, which turn out to be needed in most sessions with the interpreter.
# Добавить автодополнение и сохранение истории команд в ваш Python
# интерактивный интерпретатор. Требуется Python 2.0+ и readline. Автодополнение
# привязано к клавише Esc по умолчанию (можно изменить – см. документацию readline).
#
# Сохраните файл в ~/.pystartup и установите переменную окружения, указывающую на
# для этого: "export PYTHONSTARTUP=~/.pystartup" в bash.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
13.4. Альтернативы интерактивному интерпретатору¶Alternatives to the Interactive Interpreter
Эта возможность является огромным шагом вперед по сравнению с более ранними версиями интерпретатора; однако остаются некоторые пожелания: было бы хорошо, если бы правильный отступ предлагался на строках продолжения (парсер знает, требуется ли следующий токен отступа). Механизм автодополнения мог бы использовать таблицу символов интерпретатора. Также была бы полезна команда для проверки (или даже предложения) соответствующих скобок, кавычек и т.д.
Одной из альтернатив с расширенными возможностями, которая существует уже довольно давно, является IPython. Он предлагает автодополнение по табуляции, исследование объектов и расширенное управление историей. Его также можно тщательно настраивать и встраивать в другие приложения. Другая подобная среда с расширенными возможностями – bpython.
Сноски
| [1] | Python will execute the contents of a file identified by the PYTHONSTARTUP environment variable when you start an interactive interpreter. To customize Python even for non-interactive mode, see The Customization Modules. |