formations/python/python2/formation/snippets/cli.py

74 lines
2.2 KiB
Python

#!/usr/bin/env python
# -*- coding: utf8 -*-
"""Command line interpreter
"""
import cmd
# ____________________________________________________________
# this Cli is a model of a basic use of a simple cmd
class Cli(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.doc_header = "Documented commands (type help <command>):"
self.undoc_header = "Undocumented commands"
self.prompt = "#Prompt> "
self.intro = """cli (command line interpreter)
(type help or ? for commands list)"""
self.ruler = "-"
def emptyline(self):
print "Type 'exit' to finish withe the session or type ? for help."
def default(self, line):
print "unknown command prefix"
print "*** unknown syntax : %s (type 'help' for help for a list of valid commands)"%line
self.emptyline()
def do_exit(self, line):
"""Exits from the console"""
return True
def do_quit(self, line):
return True
def do_EOF(self, args):
"""Exit on system end of file character"""
return True
# ____________________________________________________________
# commands pre and post actions
# def precmd(self, line):
# return line
# def postcmd(self, stop, line):
# # if there is a problem, just return True : it stops everythings
# stop = True
# return stop # quit if stop == True
# ____________________________________________________________
# program pre and post actions
# def preloop(self):
# # action for the beginning of the program
# pass
# def postloop(self):
# # action for the end of the program
# print "exit cli"
# ____________________________________________________________
class HelloCli(Cli):
def input_hello(self, line):
return line.replace(",", " and ")
def output_hello(self, result):
print result
def do_hello(self, line):
self.output_hello("hello, " + self.input_hello(line))
#return False # if you want to stay into the cli
return True # if you want to exit
if __name__ == '__main__':
prompt = HelloCli()
prompt.cmdloop("intro, modifies Cmd.intro")