Skip to content

Command history and completion for CLI

Ben Toogood edited this page May 28, 2013 · 1 revision

Introduction

Out of the box, the gaffer command line app "gaffer cli" isn't particularly useable - there's no tab-to-complete or history or line editing. This is because the python module responsible for such things isn't compatible with the BSD license, and therefore can't be distributed with Gaffer. This short how-to provides a workaround for that.

Enabling readline and command completion

Chances are you already have a system install of python, and it has the readline module. If so, the following startup script will locate it and set it up, along with some nice tab-based completion. Just cut and paste the text into a ~/gaffer/startup/cli/completion.py file.

import imp
import sys

# import readline. first try a normal import, and if that fails then 
# attempt to locate and import readline from a system level install.
try :
        import readline
except ImportError :
        pythonVersion = ".".join( [ str( x ) for x in sys.version_info[:2] ] )
        f = imp.find_module( "readline", [ "/usr/lib/python%s/lib-dynload" % pythonVersion ] )
        readline = imp.load_module( "readline", *f )

# bind tab as a completion trigger
if "libedit" in readline.__doc__ :
        readline.parse_and_bind( "bind ^I rl_complete" )
else :
        readline.parse_and_bind( "tab: complete" )
        
# register a custom completer that allows tab to work for indentation
# as well as completion.

import rlcompleter
class __IndentingCompleter( rlcompleter.Completer ) :

        def complete( self, text, state ) :
        
                if not text or text.isspace() :
                        return "\t" if not state else None
                else :
                        return rlcompleter.Completer.complete( self, text, state )

readline.set_completer( __IndentingCompleter().complete )