Cmdparse module in Python
Last Updated :
25 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
Import module in Python
In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Pythonâs import st
3 min read
Docopt module in Python
Docopt is a command line interface description module. It helps you define a interface for a command-line application and generates parser for it. The interface message in docopt is a formalized help message. Installation You can install docopt module in various ways, pip is one of the best ways to
3 min read
__future__ Module in Python
__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. I
4 min read
Getopt module in Python
The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is in general used for parsing an argument sequence such as sys.argv. In other words, this module helps scripts to parse command-line arguments in sys.argv. It works similar t
2 min read
Functools module in Python
Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes - partial and partialmethod. Partial class A partial function
6 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python getpass module
When we use terminal based application with some security credentials that use password before execution the application, Then It will be done with Python Getpass module. In this article we are going see how to use Getpass module. Getpass module provides two function: getpass.getpass()getpass.getuse
2 min read
Python Module Index
Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
External Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read