×

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 hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 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.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Python Logging Maxbytes

Python: 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 a faster way....

6 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.