Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 5e7a892ad4
Fetching contributors…

Cannot retrieve contributors at this time

249 lines (146 sloc) 7.251 kb

:mod:`readline` --- GNU readline interface

The :mod:`readline` module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly or via the :mod:`rlcompleter` module. Settings made using this module affect the behaviour of both the interpreter's interactive prompt and the prompts offered by the :func:`raw_input` and :func:`input` built-in functions.

Note

On MacOS X the :mod:`readline` module can be implemented using the libedit library instead of GNU readline.

The configuration file for libedit is different from that of GNU readline. If you programmatically load configuration strings you can check for the text "libedit" in :const:`readline.__doc__` to differentiate between GNU readline and libedit.

The :mod:`readline` module defines the following functions:

Example

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

import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
try:
    readline.read_history_file(histfile)
except IOError:
    pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile

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

import code
import readline
import atexit
import os

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 IOError:
                pass
            atexit.register(self.save_history, histfile)

    def save_history(self, histfile):
        readline.write_history_file(histfile)
Jump to Line
Something went wrong with that request. Please try again.