Cmdparse module in Python
Last Updated :
28 Apr, 2025
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:
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:
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read