1.. _tut-interacting: 2 3************************************************** 4Interactive Input Editing and History Substitution 5************************************************** 6 7Some versions of the Python interpreter support editing of the current input 8line and history substitution, similar to facilities found in the Korn shell and 9the GNU Bash shell. This is implemented using the `GNU Readline`_ library, 10which supports Emacs-style and vi-style editing. This library has its own 11documentation which I won't duplicate here; however, the basics are easily 12explained. The interactive editing and history described here are optionally 13available in the Unix and Cygwin versions of the interpreter. 14 15This chapter does *not* document the editing facilities of Mark Hammond's 16PythonWin package or the Tk-based environment, IDLE, distributed with Python. 17The command line history recall which operates within DOS boxes on NT and some 18other DOS and Windows flavors is yet another beast. 19 20 21.. _tut-lineediting: 22 23Line Editing 24============ 25 26If supported, input line editing is active whenever the interpreter prints a 27primary or secondary prompt. The current line can be edited using the 28conventional Emacs control characters. The most important of these are: 29:kbd:`C-A` (Control-A) moves the cursor to the beginning of the line, :kbd:`C-E` 30to the end, :kbd:`C-B` moves it one position to the left, :kbd:`C-F` to the 31right. Backspace erases the character to the left of the cursor, :kbd:`C-D` the 32character to its right. :kbd:`C-K` kills (erases) the rest of the line to the 33right of the cursor, :kbd:`C-Y` yanks back the last killed string. 34:kbd:`C-underscore` undoes the last change you made; it can be repeated for 35cumulative effect. 36 37 38.. _tut-history: 39 40History Substitution 41==================== 42 43History substitution works as follows. All non-empty input lines issued are 44saved in a history buffer, and when a new prompt is given you are positioned on 45a new line at the bottom of this buffer. :kbd:`C-P` moves one line up (back) in 46the history buffer, :kbd:`C-N` moves one down. Any line in the history buffer 47can be edited; an asterisk appears in front of the prompt to mark a line as 48modified. Pressing the :kbd:`Return` key passes the current line to the 49interpreter. :kbd:`C-R` starts an incremental reverse search; :kbd:`C-S` starts 50a forward search. 51 52 53.. _tut-keybindings: 54 55Key Bindings 56============ 57 58The key bindings and some other parameters of the Readline library can be 59customized by placing commands in an initialization file called 60:file:`~/.inputrc`. Key bindings have the form :: 61 62 key-name: function-name 63 64or :: 65 66 "string": function-name 67 68and options can be set with :: 69 70 set option-name value 71 72For example:: 73 74 # I prefer vi-style editing: 75 set editing-mode vi 76 77 # Edit using a single line: 78 set horizontal-scroll-mode On 79 80 # Rebind some keys: 81 Meta-h: backward-kill-word 82 "\C-u": universal-argument 83 "\C-x\C-r": re-read-init-file 84 85Note that the default binding for :kbd:`Tab` in Python is to insert a :kbd:`Tab` 86character instead of Readline's default filename completion function. If you 87insist, you can override this by putting :: 88 89 Tab: complete 90 91in your :file:`~/.inputrc`. (Of course, this makes it harder to type indented 92continuation lines if you're accustomed to using :kbd:`Tab` for that purpose.) 93 94.. index:: 95 module: rlcompleter 96 module: readline 97 98Automatic completion of variable and module names is optionally available. To 99enable it in the interpreter's interactive mode, add the following to your 100startup file: [#]_ :: 101 102 import rlcompleter, readline 103 readline.parse_and_bind('tab: complete') 104 105This binds the :kbd:`Tab` key to the completion function, so hitting the 106:kbd:`Tab` key twice suggests completions; it looks at Python statement names, 107the current local variables, and the available module names. For dotted 108expressions such as ``string.a``, it will evaluate the expression up to the 109final ``'.'`` and then suggest completions from the attributes of the resulting 110object. Note that this may execute application-defined code if an object with a 111:meth:`__getattr__` method is part of the expression. 112 113A more capable startup file might look like this example. Note that this 114deletes the names it creates once they are no longer needed; this is done since 115the startup file is executed in the same namespace as the interactive commands, 116and removing the names avoids creating side effects in the interactive 117environment. You may find it convenient to keep some of the imported modules, 118such as :mod:`os`, which turn out to be needed in most sessions with the 119interpreter. :: 120 121 # Add auto-completion and a stored history file of commands to your Python 122 # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is 123 # bound to the Esc key by default (you can change it - see readline docs). 124 # 125 # Store the file in ~/.pystartup, and set an environment variable to point 126 # to it: "export PYTHONSTARTUP=~/.pystartup" in bash. 127 128 import atexit 129 import os 130 import readline 131 import rlcompleter 132 133 historyPath = os.path.expanduser("~/.pyhistory") 134 135 def save_history(historyPath=historyPath): 136 import readline 137 readline.write_history_file(historyPath) 138 139 if os.path.exists(historyPath): 140 readline.read_history_file(historyPath) 141 142 atexit.register(save_history) 143 del os, atexit, readline, rlcompleter, save_history, historyPath 144 145 146.. _tut-commentary: 147 148Alternatives to the Interactive Interpreter 149=========================================== 150 151This facility is an enormous step forward compared to earlier versions of the 152interpreter; however, some wishes are left: It would be nice if the proper 153indentation were suggested on continuation lines (the parser knows if an indent 154token is required next). The completion mechanism might use the interpreter's 155symbol table. A command to check (or even suggest) matching parentheses, 156quotes, etc., would also be useful. 157 158One alternative enhanced interactive interpreter that has been around for quite 159some time is IPython_, which features tab completion, object exploration and 160advanced history management. It can also be thoroughly customized and embedded 161into other applications. Another similar enhanced interactive environment is 162bpython_. 163 164 165.. rubric:: Footnotes 166 167.. [#] Python will execute the contents of a file identified by the 168 :envvar:`PYTHONSTARTUP` environment variable when you start an interactive 169 interpreter. To customize Python even for non-interactive mode, see 170 :ref:`tut-customize`. 171 172 173.. _GNU Readline: https://tiswww.case.edu/php/chet/readline/rltop.html 174.. _IPython: http://ipython.scipy.org/ 175.. _bpython: http://www.bpython-interpreter.org/ 176