Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1a6cb30

Browse files
committed
Issue #5845: Enable tab-completion in the interactive interpreter by default, thanks to a new sys.__interactivehook__.
(original patch by Éric Araujo)
1 parent 4c14b5d commit 1a6cb30

9 files changed

Lines changed: 143 additions & 165 deletions

File tree

Doc/library/readline.rst

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -190,28 +190,32 @@ Example
190190

191191
The following example demonstrates how to use the :mod:`readline` module's
192192
history reading and writing functions to automatically load and save a history
193-
file named :file:`.pyhist` from the user's home directory. The code below would
194-
normally be executed automatically during interactive sessions from the user's
195-
:envvar:`PYTHONSTARTUP` file. ::
193+
file named :file:`.python_history` from the user's home directory. The code
194+
below would normally be executed automatically during interactive sessions
195+
from the user's :envvar:`PYTHONSTARTUP` file. ::
196196

197+
import atexit
197198
import os
198199
import readline
199-
histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
200+
201+
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
200202
try:
201203
readline.read_history_file(histfile)
202204
except FileNotFoundError:
203205
pass
204-
import atexit
206+
205207
atexit.register(readline.write_history_file, histfile)
206-
del os, histfile
208+
209+
This code is actually automatically run when Python is run in
210+
:ref:`interactive mode <tut-interactive>` (see :ref:`rlcompleter-config`).
207211

208212
The following example extends the :class:`code.InteractiveConsole` class to
209213
support history save/restore. ::
210214

211-
import code
212-
import readline
213215
import atexit
216+
import code
214217
import os
218+
import readline
215219

216220
class HistoryConsole(code.InteractiveConsole):
217221
def __init__(self, locals=None, filename="<console>",

Doc/library/rlcompleter.rst

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,10 @@ Example::
2727
readline.__name__ readline.parse_and_bind(
2828
>>> readline.
2929

30-
The :mod:`rlcompleter` module is designed for use with Python's interactive
31-
mode. A user can add the following lines to his or her initialization file
32-
(identified by the :envvar:`PYTHONSTARTUP` environment variable) to get
33-
automatic :kbd:`Tab` completion::
34-
35-
try:
36-
import readline
37-
except ImportError:
38-
print("Module readline not available.")
39-
else:
40-
import rlcompleter
41-
readline.parse_and_bind("tab: complete")
30+
The :mod:`rlcompleter` module is designed for use with Python's
31+
:ref:`interactive mode <tut-interactive>`. Unless Python is run with the
32+
:option:`-S` option, the module is automatically imported and configured
33+
(see :ref:`rlcompleter-config`).
4234

4335
On platforms without :mod:`readline`, the :class:`Completer` class defined by
4436
this module can still be used for custom purposes.

Doc/library/site.rst

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,23 @@ empty, and the path manipulations are skipped; however the import of
111111
:mod:`sitecustomize` and :mod:`usercustomize` is still attempted.
112112

113113

114+
.. _rlcompleter-config:
115+
116+
Readline configuration
117+
----------------------
118+
119+
On systems that support :mod:`readline`, this module will also import and
120+
configure the :mod:`rlcompleter` module, if Python is started in
121+
:ref:`interactive mode <tut-interactive>` and without the :option:`-S` option.
122+
The default behavior is enable tab-completion and to use
123+
:file:`~/.python_history` as the history save file. To disable it, override
124+
the :data:`sys.__interactivehook__` attribute in your :mod:`sitecustomize`
125+
or :mod:`usercustomize` module or your :envvar:`PYTHONSTARTUP` file.
126+
127+
128+
Module contents
129+
---------------
130+
114131
.. data:: PREFIXES
115132

116133
A list of prefixes for site-packages directories.
@@ -153,8 +170,7 @@ empty, and the path manipulations are skipped; however the import of
153170

154171
Adds all the standard site-specific directories to the module search
155172
path. This function is called automatically when this module is imported,
156-
unless the :program:`python` interpreter was started with the :option:`-S`
157-
flag.
173+
unless the Python interpreter was started with the :option:`-S` flag.
158174

159175
.. versionchanged:: 3.3
160176
This function used to be called unconditionnally.

Doc/library/sys.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,16 @@ always available.
679679
.. versionadded:: 3.1
680680

681681

682+
.. data:: __interactivehook__
683+
684+
When present, this function is automatically called (with no arguments)
685+
when the interpreter is launched in :ref:`interactive mode <tut-interactive>`.
686+
This is done after the :envvar:`PYTHONSTARTUP` file is read, so that you
687+
can set this hook there.
688+
689+
.. versionadded:: 3.4
690+
691+
682692
.. function:: intern(string)
683693

684694
Enter *string* in the table of "interned" strings and return the interned string

Doc/tutorial/interactive.rst

Lines changed: 16 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -7,140 +7,27 @@ Interactive Input Editing and History Substitution
77
Some versions of the Python interpreter support editing of the current input
88
line and history substitution, similar to facilities found in the Korn shell and
99
the GNU Bash shell. This is implemented using the `GNU Readline`_ library,
10-
which supports Emacs-style and vi-style editing. This library has its own
11-
documentation which I won't duplicate here; however, the basics are easily
12-
explained. The interactive editing and history described here are optionally
13-
available in the Unix and Cygwin versions of the interpreter.
14-
15-
This chapter does *not* document the editing facilities of Mark Hammond's
16-
PythonWin package or the Tk-based environment, IDLE, distributed with Python.
17-
The command line history recall which operates within DOS boxes on NT and some
18-
other DOS and Windows flavors is yet another beast.
19-
20-
21-
.. _tut-lineediting:
22-
23-
Line Editing
24-
============
25-
26-
If supported, input line editing is active whenever the interpreter prints a
27-
primary or secondary prompt. The current line can be edited using the
28-
conventional 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`
30-
to the end, :kbd:`C-B` moves it one position to the left, :kbd:`C-F` to the
31-
right. Backspace erases the character to the left of the cursor, :kbd:`C-D` the
32-
character to its right. :kbd:`C-K` kills (erases) the rest of the line to the
33-
right 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
35-
cumulative effect.
36-
37-
38-
.. _tut-history:
39-
40-
History Substitution
41-
====================
42-
43-
History substitution works as follows. All non-empty input lines issued are
44-
saved in a history buffer, and when a new prompt is given you are positioned on
45-
a new line at the bottom of this buffer. :kbd:`C-P` moves one line up (back) in
46-
the history buffer, :kbd:`C-N` moves one down. Any line in the history buffer
47-
can be edited; an asterisk appears in front of the prompt to mark a line as
48-
modified. Pressing the :kbd:`Return` key passes the current line to the
49-
interpreter. :kbd:`C-R` starts an incremental reverse search; :kbd:`C-S` starts
50-
a forward search.
10+
which supports various styles of editing. This library has its own
11+
documentation which we won't duplicate here.
5112

5213

5314
.. _tut-keybindings:
5415

55-
Key Bindings
56-
============
57-
58-
The key bindings and some other parameters of the Readline library can be
59-
customized by placing commands in an initialization file called
60-
:file:`~/.inputrc`. Key bindings have the form ::
61-
62-
key-name: function-name
63-
64-
or ::
65-
66-
"string": function-name
67-
68-
and options can be set with ::
69-
70-
set option-name value
71-
72-
For 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
16+
Tab Completion and History Editing
17+
==================================
7918

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-
85-
Note that the default binding for :kbd:`Tab` in Python is to insert a :kbd:`Tab`
86-
character instead of Readline's default filename completion function. If you
87-
insist, you can override this by putting ::
88-
89-
Tab: complete
90-
91-
in your :file:`~/.inputrc`. (Of course, this makes it harder to type indented
92-
continuation lines if you're accustomed to using :kbd:`Tab` for that purpose.)
93-
94-
.. index::
95-
module: rlcompleter
96-
module: readline
97-
98-
Automatic completion of variable and module names is optionally available. To
99-
enable it in the interpreter's interactive mode, add the following to your
100-
startup file: [#]_ ::
101-
102-
import rlcompleter, readline
103-
readline.parse_and_bind('tab: complete')
104-
105-
This 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,
107-
the current local variables, and the available module names. For dotted
108-
expressions such as ``string.a``, it will evaluate the expression up to the
109-
final ``'.'`` and then suggest completions from the attributes of the resulting
110-
object. Note that this may execute application-defined code if an object with a
111-
:meth:`__getattr__` method is part of the expression.
112-
113-
A more capable startup file might look like this example. Note that this
114-
deletes the names it creates once they are no longer needed; this is done since
115-
the startup file is executed in the same namespace as the interactive commands,
116-
and removing the names avoids creating side effects in the interactive
117-
environment. You may find it convenient to keep some of the imported modules,
118-
such as :mod:`os`, which turn out to be needed in most sessions with the
119-
interpreter. ::
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
19+
Completion of variable and module names is
20+
:ref:`automatically enabled <rlcompleter-config>` at interpreter startup so
21+
that the :kbd:`Tab` key invokes the completion function; it looks at
22+
Python statement names, the current local variables, and the available
23+
module names. For dotted expressions such as ``string.a``, it will evaluate
24+
the expression up to the final ``'.'`` and then suggest completions from
25+
the attributes of the resulting object. Note that this may execute
26+
application-defined code if an object with a :meth:`__getattr__` method
27+
is part of the expression. The default configuration also saves your
28+
history into a file named :file:`.python_history` in your user directory.
29+
The history will be available again during the next interactive interpreter
30+
session.
14431

14532

14633
.. _tut-commentary:
@@ -162,14 +49,6 @@ into other applications. Another similar enhanced interactive environment is
16249
bpython_.
16350

16451

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-
17352
.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
17453
.. _IPython: http://ipython.scipy.org/
17554
.. _bpython: http://www.bpython-interpreter.org/

Doc/using/cmdline.rst

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,12 @@ source.
147147

148148
If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
149149
an empty string (``""``) and the current directory will be added to the
150-
start of :data:`sys.path`.
150+
start of :data:`sys.path`. Also, tab-completion and history editing is
151+
automatically enabled, if available on your platform (see
152+
:ref:`rlcompleter-config`).
153+
154+
.. versionchanged:: 3.4
155+
Automatic enabling of tab-completion and history editing.
151156

152157
.. seealso:: :ref:`tut-invoking`
153158

@@ -438,7 +443,7 @@ conflict.
438443
is executed in the same namespace where interactive commands are executed so
439444
that objects defined or imported in it can be used without qualification in
440445
the interactive session. You can also change the prompts :data:`sys.ps1` and
441-
:data:`sys.ps2` in this file.
446+
:data:`sys.ps2` and the hook :data:`sys.__interactivehook__` in this file.
442447

443448

444449
.. envvar:: PYTHONY2K

Lib/site.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,14 @@
5858
because bar.pth comes alphabetically before foo.pth; and spam is
5959
omitted because it is not mentioned in either path configuration file.
6060
61-
After these path manipulations, an attempt is made to import a module
61+
The readline module is also automatically configured to enable
62+
completion for systems that support it. This can be overriden in
63+
sitecustomize, usercustomize or PYTHONSTARTUP.
64+
65+
After these operations, an attempt is made to import a module
6266
named sitecustomize, which can perform arbitrary additional
6367
site-specific customizations. If this import fails with an
6468
ImportError exception, it is silently ignored.
65-
6669
"""
6770

6871
import sys
@@ -452,6 +455,40 @@ def __call__(self, *args, **kwds):
452455
def sethelper():
453456
builtins.help = _Helper()
454457

458+
def enablerlcompleter():
459+
"""Enable default readline configuration on interactive prompts, by
460+
registering a sys.__interactivehook__.
461+
462+
If the readline module can be imported, the hook will set the Tab key
463+
as completion key and register ~/.python_history as history file.
464+
This can be overriden in the sitecustomize or usercustomize module,
465+
or in a PYTHONSTARTUP file.
466+
"""
467+
def register_readline():
468+
import atexit
469+
try:
470+
import readline
471+
import rlcompleter
472+
except ImportError:
473+
return
474+
475+
# Reading the initialization (config) file may not be enough to set a
476+
# completion key, so we set one first and then read the file
477+
if 'libedit' in getattr(readline, '__doc__', ''):
478+
readline.parse_and_bind('bind ^I rl_complete')
479+
else:
480+
readline.parse_and_bind('tab: complete')
481+
readline.read_init_file()
482+
483+
history = os.path.join(os.path.expanduser('~'), '.python_history')
484+
try:
485+
readline.read_history_file(history)
486+
except IOError:
487+
pass
488+
atexit.register(readline.write_history_file, history)
489+
490+
sys.__interactivehook__ = register_readline
491+
455492
def aliasmbcs():
456493
"""On Windows, some default encodings are not provided by Python,
457494
while they are always available as "mbcs" in each locale. Make
@@ -571,6 +608,7 @@ def main():
571608
setquit()
572609
setcopyright()
573610
sethelper()
611+
enablerlcompleter()
574612
aliasmbcs()
575613
execsitecustomize()
576614
if ENABLE_USER_SITE:

0 commit comments

Comments
 (0)