Jérôme Belleman
Home  •  Tools  •  Posts  •  Talks  •  Travels  •  Graphics  •  About Me

Python Shell Command Lines and External Editors

9 Dec 2013

This post describes a way to add the capability to interpreters you implement with the cmd Python module to edit command lines with custom external editors.

1 Context

The idea is to provide to your own command line interpreters which you implement with the cmd Python module that feature which shells such as bash with Vi key bindings offer when you type Esc v : an editor opens in the terminal where you used your shell, with the command line you wrote so far in a temporary file. Edit this command line in the comfort of your editor, save the temporary file, and its contents will be used to replace the command line of your shell.

It's a tremendous feature for writing complex command lines, or even complex sequences thereof. I've set my editor to Vim and, being comfortable with macros, I sometimes prefer generating a long sequence of commands rather than writing more complex shell control structures to avoid accidents. When I started writing interpreters in Python with the cmd module I thought, why not bring this very useful feature there too?

2 Using the readline Module

The readline module provides the insert_text function but it cannot be used everywhere. A question in Stack Overflow asked, Is it possible to prefill a input() in Python 3's Command Line Interface? It explains how it should be called from a pre_input_hook, which should be unset again afterwards. Integrated with the Cmd module, it's all arranged as follows:

3 References