Open In App

Cmdparse module in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

  • Command line interface is portable and can be run everywhere. 
     
  • CPU and memory resources are far for cheaper than GUI interface. 
     
  • It is easier to open the file with command line rather than getting into drivers and searching for menu. 
     
  • It is far faster to create Text oriented documents. 
     

 

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. 
 

  • Create Command: The first part of a line of text entered at the interpreter prompt is a command. The longest string of characters contained in the identchars member is Command. 
    Non accented letters, digits and the underscore symbol are default identchars. The end of the line is the command’s parameters. 
     
  • Parameter: Only one extra parameter should be taken by do_xxx method and corresponds to the part of the string entered by the user after the command name. 
     
  • Errors: Following format is used by the interpreter to signal errors: 
     
*** : 
  •  
  • Return Value: In the most common case: commands shouldn’t return a value. When you want to exit the interpreter loop any command that returns a true value stops the interpreter is an exception.
    Example: 
     

Python3




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:
 

  • cmdparser.cmdparser 
     
  • cmdparser.datetimeparse 
     

 

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:
 

Python3




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:
 

python-cmdparse-1

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:
 

Python3




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:
 

python-cmdparser-2

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

  • Token: When one of the sets of fix value is suitable, this is useful, where the list may be fixed or dynamic. The get_values() method should be overridden to return a list of valid tokens as strings. 
     
  • Anytoken: It is similar to Token, but any string is to be expected. Validation can be performed via the validate() method, but validate() method doesn’t allow tab-completion as it’s only called once the entire command is parsed. There is also a convert() method should it be required 
     
  • AnyTokenString: Similar to AnyToken but all remaining items on the command line are consumed. 
     
  • Subtree: It matches the entire command subtree and stores the result against the specified token in the fields dictionary. The command specification string should be passed to the constructor, and type classes will override the convert() method and interpret the command in some way (although this is strictly optional).
    Decorators are present for use with command handlers derived from cmd.Cmd which allows command strings to be automatically extracted from docstring help text, and allowing command parsing and completion to be added to the command-handling methods of the class. 
    Various methods of the form do_XXX() are implemented to implement the cmd.Cmd class.
     

Python3




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

  • Datetimeparse module adds specific token types to parse human-readable specifications of date and time. Absolute and relative both types of dates are specified and this is converted to other instances as appropriate. 
    Some examples are 
     
1:35 on friday last week
11 feb 2019
  • Classes currently defined are: 
    • DateSubtree: It includes the literal date (2020-03-14), days of the week related to current day (Saturday last week), descriptive version (26th june 2019), as well as yesterday, today and tomorrow along with parse calendar date. The return value is datetime.date instance. 
       
    • TimeSubtree: Time of day in 12 or 24-hour format is parsed by TimeSubtree. The returned value is as returned by time.localtime(). 
       
    • RelativeTimeSubtree: The returned value is an instance of cmdparser.DateDelta, which is a wrapper class containing a datetime.timedelta. It Parses phrases which indicate a time offset from the present time, such as 3 days and 2 hours ago. 
       
    • DateTimeSubtree: datetime.datetime instance is the returned value.DateTimeSubtree Parses specifications of a date and time, accepting either a combination of DateSubtree and TimeSubtree phrases, or a RelativeTimeSubtree phrase; in the latter case, the time is taken in relative to the current time. 
       
    • CLassCalenderPeriodSubtree: Parses specifications of calendar periods in the past. The returned value is a 2-tuple of datetime.date instances representing the range of dates specified, where the first date is inclusive and the second exclusive. 
       


Last Updated : 28 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads