interactive.md
1> **Источник:** https://python-all.ru/3.2/tutorial/interactive.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# 13. Интерактивное редактирование ввода и подстановка из истории89Некоторые версии интерпретатора Python поддерживают редактирование текущей строки ввода и подстановку из истории, аналогично тому, что есть в оболочках Korn и GNU Bash. Это реализовано с помощью библиотеки [GNU Readline](https://python-all.ru/3.2/tutorial/interactive.html), которая поддерживает редактирование в стиле Emacs и vi. У этой библиотеки есть собственная документация, которую я здесь не буду повторять; однако основные принципы легко объяснить. Описанные здесь интерактивное редактирование и подстановка из истории опционально доступны в версиях интерпретатора для Unix и Cygwin.1011В этой главе *не* описываются средства редактирования пакета PythonWin Марка Хаммонда или среды IDLE на основе Tk, распространяемой вместе с Python. Вызов истории командной строки, работающий в окнах DOS на NT и некоторых других версиях DOS и Windows, – это совсем другое дело.1213## 13.1. Редактирование строки1415If 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.1617## 13.2. Подстановка из истории1819History 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.2021## 13.3. Привязки клавиш2223The 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 form2425```python26key-name: function-name27```2829или3031```python32"string": function-name33```3435а параметры можно задать с помощью3637```python38set option-name value39```4041Например:4243```python44# Я предпочитаю редактирование в стиле vi:45set editing-mode vi4647# Редактирование одной строкой:48set horizontal-scroll-mode On4950# Переназначить некоторые клавиши:51Meta-h: backward-kill-word52"\C-u": universal-argument53"\C-x\C-r": re-read-init-file54```5556Note 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 putting5758```python59Tab: complete60```6162in your `~/.inputrc`. (Of course, this makes it harder to type indented continuation lines if you’re accustomed to using `Tab` for that purpose.)6364Автоматическое дополнение имён переменных и модулей опционально доступно. Чтобы включить его в интерактивном режиме интерпретатора, добавьте следующее в ваш файл запуска: [\[1\]](https://python-all.ru/3.2/tutorial/interactive.html#id2)6566```python67import rlcompleter, readline68readline.parse_and_bind('tab: complete')69```7071This 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__()`](https://python-all.ru/3.2/reference/datamodel.html#object.__getattr__) method is part of the expression.7273A 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`](https://python-all.ru/3.2/library/os.html#module-os), which turn out to be needed in most sessions with the interpreter.7475```python76# Добавить автодополнение и сохранение истории команд в ваш Python77# интерактивный интерпретатор. Требуется Python 2.0+ и readline. Автодополнение78# привязано к клавише Esc по умолчанию (можно изменить – см. документацию readline).79#80# Сохраните файл в ~/.pystartup и установите переменную окружения, указывающую на81# для этого: "export PYTHONSTARTUP=~/.pystartup" в bash.8283import atexit84import os85import readline86import rlcompleter8788historyPath = os.path.expanduser("~/.pyhistory")8990def save_history(historyPath=historyPath):91 import readline92 readline.write_history_file(historyPath)9394if os.path.exists(historyPath):95 readline.read_history_file(historyPath)9697atexit.register(save_history)98del os, atexit, readline, rlcompleter, save_history, historyPath99```100101## 13.4. Альтернативы интерактивному интерпретатору102103Эта возможность является огромным шагом вперед по сравнению с более ранними версиями интерпретатора; однако остаются некоторые пожелания: было бы хорошо, если бы правильный отступ предлагался на строках продолжения (парсер знает, требуется ли следующий токен отступа). Механизм автодополнения мог бы использовать таблицу символов интерпретатора. Также была бы полезна команда для проверки (или даже предложения) соответствующих скобок, кавычек и т.д.104105Одной из альтернатив с расширенными возможностями, которая существует уже довольно давно, является [IPython](https://python-all.ru/3.2/tutorial/interactive.html). Он предлагает автодополнение по табуляции, исследование объектов и расширенное управление историей. Его также можно тщательно настраивать и встраивать в другие приложения. Другая подобная среда с расширенными возможностями – [bpython](https://python-all.ru/3.2/tutorial/interactive.html).106107Сноски108109| [\[1\]](https://python-all.ru/3.2/tutorial/interactive.html#id1) | Python will execute the contents of a file identified by the [`PYTHONSTARTUP`](https://python-all.ru/3.2/using/cmdline.html#envvar-PYTHONSTARTUP) environment variable when you start an interactive interpreter. To customize Python even for non-interactive mode, see [*The Customization Modules*](https://python-all.ru/3.2/tutorial/interpreter.html#tut-customize). |110| --- | --- |111