Open In App

Cmdparse module in Python

The Class which provides a simple framework for writing line-oriented command interpreters is called cmd class. These are often useful for administrative tools, prototypes and test harnesses that will later be wrapped in a more sophisticated interface. The command-line interface can be easily made using the cmd Module.
Graphical user interfaces are used so much in these days that a command-line interpreter seems antique. Command-line interface can have several advantages: 
 

 



Cmd Class

The module defines only one class: the Cmd class. Command-line interpreter is created sub-classing the cmd.Cmd class. A Cmd instance or subclass instance can be considered as a line-oriented interpreter framework. 
 

*** : 




def add(self, d):
    k = d.split()
    if len(k)!= 2:
       print "*** invalid number of arguments"
       return
    try:
       k = [int(i) for i in k]
    except ValueError:
       print "*** arguments should be numbers"
       return
    print k[0]+k[1]

 



Cmdparse Module

The cmdparser package contains two modules that are useful for writing text command parsers. 
This module particularly uses the builtin Python cmd module. The package consists of two modules:
 

 

Installation

We can install cmdparse package from PyPI.For example 
 

pip install cmdparse

 

cmdparse OVERVIEW

Cmd module allows creating parse tree from textual command specification like below 
 

chips( spam | ham [eggs] | beans [eggs [...]] )

The particular command string can be checked using these parse trees. Also, it allows valid completion of partial command string to be listed.
Example:
 




from cmdparser import cmdparser
 
parse_tree = cmdparser.parse_spec("abc (def|ghi) <jkl> [mno]")
 
# Returns None to indicate
# successful parse
parse_tree.check_match(("abc", "def", "anything"))
 
# Returns an appropriate
# parsing error message
parse_tree.check_match(("abc", "ghi", "anything", "pqr"))
 
# Returns the list ["def", "ghi"]
parse_tree.get_completions(("abc", ))

Output:
 

Dynamic tokens can be set up where the list of strings accepted can change over time, or where arbitrary strings or lists of strings can be accepted While dealing with a fixed token string. Check the module’s docstrings for specifics of the classes available, but as an example:
 




from cmdparser import cmdparser
 
 
class fruitToken(cmdparser.Token):
     
    def get_values(self, context):
        # Static list here, but could
        # easily be dynamic
        return ["raspberry", "orange", "mango",
                "grapes", "apple", "banana"]
 
def my_ident_factory(token):
     
    if token == "number":
        return cmdparser.IntegerToken(token)
     
    elif token == "fruit":
        return fruitToken(token)
     
    return None
 
parse_tree = cmdparser.parse_tree("take <number> <fruit> bags",
                                  ident_factory = my_ident_factory)
 
# Returns None to indicate successful
# parse, and the "cmd_fields" dict will
# be initialised as:
# { "take": ["take"], "<number>": ["23"],
#   "<fruit>": ["apple"], "bags": ["bags"] }
cmd_fields = {}
 
parse_tree.check_match(("take", "23",
                        "apple", "bags"),
                       fields = cmd_fields)
 
# Returns an appropriate
# parsing error message
parse_tree.check_match(("take", "all",
                        "raspberry", "bags"))
 
# Returns the list ["raspberry",
# "orange", "mango", ..., "banana"]
parse_tree.get_completions(("take", "5"))

Output:
 

Four classes are available which are suitable base classes for user-derived tokens: 
 




from cmdparser import cmdparser
 
@cmdparser.CmdClassDecorator()
class CommandHandler(cmd.Cmd):
 
    @cmdparser.CmdMethodDecorator():
    def do_command(self, args, fields):
        """command ( add | delete ) <name>
 
        The example explains the use of
        command to demonstrate use of the cmd
        decorators.
        """
 
        # Method body - it will only be called
        # if a command parses successfully according
        # to the specification above.

datetimeparse OVERVIEW

1:35 on friday last week
11 feb 2019

Article Tags :