×

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

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python math.cos and math.acos function

Math.cos() function In Python, the Math module is used for performing the mathematical operations. It includes the math.cos() function that is used for obtaining the cosine value of an angle in...

3 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

How to create a dictionary in Python?

How to create a dictionary in python Dictionary is a data structure in Python that represents our data in the form of keys and values. Each value in a dictionary can be...

5 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized....

6 minutes read.