×

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as a default for interactive quick handling, modification of commands and completion of commands.

Processing Command

The interpreter utilises a loop to read, parse and then send the command to the appropriate command manager, all lines from the input. Two portions of input lines are analysed. The command and any other line text. The only parameter to be called "bar" is if the user types a command foo bar and your class contains a method called do foo().

The file end marker will be sent to do EOF (). The application will quit cleanly when a command manager returns a true value. So make sure you implement do EOF() and return True to a clean path out of your interpreter.

The greet command provides this basic example program:

SYNTAX

import cmd


class HelloWorld(cmd.Cmd):
    """Simple command processor example."""
    
    def do_greet(self, line):
        print "hello"
    
    def do_EOF(self, line):
        return True


if __name__ == '__main__':
    HelloWorld().cmdloop()

By interactive execution, we can illustrate how instructions are sent and how some of the features of Cmd are shown free.

SYNTAX

$ python cmd_simple.py
(Cmd)

The first thing to notice is the prompt command (Cmd). The prompt can be set by the prompt. The prompt. The new value for the next command is utilised when the prompt changes as consequence of a command processor.

SYNTAX

(Cmd) help


Undocumented commands:
======================
EOF  greet  help

Cmd contains the help command. It shows the list of possible commands without any parameters. The output, if available, is more verbose and limited to detail of the command if you have a command you wish to help with.

If the greet command is used, do greet() is called to handle it:

SYNTAX

(Cmd) greet
Hello

When a command processor is not included in your class, the default() function is invoked as argument with the whole input line. The integrated default() implementation reports an error.

SYNTAX

(Cmd) foo *** Unknown syntax: foo

As do EOF() returns True, Ctrl-D will remove us from the interpreter by typing it.

SYNTAX

(Cmd) ^D$

Command Arguments

This example version offers some improvements for removing some of the annoyances and adding support for the greeting command.

SYNTAX

import cmd


class HelloWorld(cmd.Cmd):
    """Simple command processor example."""
    
    def do_greet(self, person):
        """greet [person]
        Greet the named person"""
        if person:
            print "hi,", person
        else:
            print 'hi'
    
    def do_EOF(self, line):
        return True
    
    def postloop(self):
        print


if __name__ == '__main__':
    HelloWorld().cmdloop()

Let's see the assistance first. The docstring that has been added to do greet() becomes the command help text:

OUTPUT

$ python cmd_arguments.py
(Cmd) help


Documented commands (type help ):
========================================
greet


Undocumented commands:
======================
EOF  help


(Cmd) help greet
greet [person]
        Greet the named person

The result displays an optional greeting command parameter, person. Although the parameter is optional to the command, the command and the callback procedure are different. The method takes the argument, however the value is occasionally an empty string. To decide if an empty argument is true or do any additional parsing and processing of the command, the command processor is left to do. In this example, the greeting will be customised if the name of a person is supplied.

OUTPUT

(Cmd) greet Alice
hi, Alice
(Cmd) greet
hi

The value supplied to the command processor does not include the command itself, regardless of whether the user gives an argument or not. If several parameters are required, this simplifies parsing in the control processor.

Live Server

In the last example, it leaves something to be desired to format the assistance text. Because it originates from the docstring, our source preserves the indentation. We can change the source to eliminate the excess white space, although this would not format our application. One approach is to use the assistance handler called help greet for the greeting command (). The aid handler is requested to generate help for the identified command when available.

SYNTAX

import cmd


class HelloWorld(cmd.Cmd):
    """Simple command processor example."""
    
    def do_greet(self, person):
        if person:
            print "hi,", person
        else:
            print 'hi'
    
    def help_greet(self):
        print '\n'.join([ 'greet [person]',
                           'Greet the named person',
                           ])
    
    def do_EOF(self, line):
        return True


if __name__ == '__main__':
    HelloWorld().cmdloop()

Related Topics

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.