Examples¶
Example code.
Simple App¶
A bare-bones application demonstrating filename and environment variable
completion. You can run this example with python -m kmd.examples.myshell
.
# TAB-complete command names, help topics, filenames, and environment variables
import os
import kmd
from kmd.completions import FilenameCompletion
from kmd.completions import EnvironmentCompletion
class MyShell(kmd.Kmd):
intro = 'myshell 1.0 (type help for help)\n'
prompt = 'myshell> '
def preloop(self):
super().preloop()
self.completefilename = FilenameCompletion()
self.completeenviron = EnvironmentCompletion()
def do_cat(self, args):
"""Usage: cat <filename>"""
os.system('cat ' + args)
def do_echo(self, args):
"""Usage: echo $<varname>"""
os.system('echo ' + args)
def do_quit(self, args):
"""Usage: quit"""
return True
def do_EOF(self, args):
return True
def complete_cat(self, text, *ignored):
return self.completefilename(text)
def complete_echo(self, text, *ignored):
return self.completeenviron(text)
def help_help(self):
self.stdout.write('Usage: help [<topic>]\n')
def emptyline(self):
pass
def main():
return MyShell().run()
if __name__ == '__main__':
main()
Custom Completion¶
An implementation of environment variable completion.
# Environment variable completion
import os
from rl import completer
class EnvironmentCompletion(object):
def __init__(self):
"""Configure the readline completer
"""
if '$' not in completer.word_break_characters:
completer.word_break_characters += '$'
if '$' not in completer.special_prefixes:
completer.special_prefixes += '$'
def __call__(self, text):
"""Return environment variables matching 'text'
Variable names are returned with a leading '$' character.
The search string may start with a '$' character which is
stripped before matching.
"""
if text.startswith('$'):
text = text[1:]
return ['$'+x for x in os.environ if x.startswith(text)]