]> granicus.if.org Git - python/commitdiff
Add example that uses readline.readline().
authorSkip Montanaro <skip@pobox.com>
Sun, 23 May 2004 19:06:41 +0000 (19:06 +0000)
committerSkip Montanaro <skip@pobox.com>
Sun, 23 May 2004 19:06:41 +0000 (19:06 +0000)
Doc/lib/libreadline.tex

index cd2a80a5aa49f0d8fb21f4383e4570ef03dbabfd..34d3a4c06ff6c7175e550d596cea93f2f86fa407 100644 (file)
@@ -159,3 +159,36 @@ atexit.register(readline.write_history_file, histfile)
 del os, histfile
 \end{verbatim}
 
+The following example extends the \class{code.InteractiveConsole} class to
+support command line editing and history save/restore.
+
+\begin{verbatim}
+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)
+        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 raw_input(self, prompt=""):
+        line = readline.readline(prompt)
+        if line:
+            readline.add_history(line)
+        return line
+
+    def save_history(self, histfile):
+        readline.write_history_file(histfile)
+\end{verbatim}