2017年12月10日 星期日

[ Python 文章收集 ] cmd – Create line-oriented command processors

Source From Here 
Preface 
The cmd module contains one public class, Cmd, designed to be used as a base class for command processors such as interactive shells and other command interpreters. By default it uses readline for interactive prompt handling, command line editing, and command completion

Processing Commands 
The interpreter uses a loop to read all lines from its input, parse them, and then dispatch the command to an appropriate command handler. Input lines are parsed into two parts. The command, and any other text on the line. If the user enters a command foo bar, and your class includes a method named do_foo(), it is called with "bar" as the only argument. 

The end-of-file marker is dispatched to do_EOF(). If a command handler returns a true value, the program will exit cleanly. So to give a clean way to exit your interpreter, make sure to implement do_EOF() and have it return True. Below simple example program supports the “greet” command: 
- cmd_simple.py 
  1. #!/usr/bin/env python  
  2. import cmd  
  3.   
  4. class HelloWorld(cmd.Cmd):  
  5.     """ Simple command processor example. """  
  6.     def do_greet(self, line):  
  7.         print'Hello {}'.format(line)  
  8.   
  9.     def do_EOF(self, line):  
  10.         print "Bye!"  
  11.         return True  
  12.   
  13. if __name__ == '__main__':  
  14.     HelloWorld().cmdloop()  
By running it interactively, we can demonstrate how commands are dispatched as well as show of some of the features included in Cmd for free. 
# python cmd_simple.py
(Cmd)

The first thing to notice is the command prompt, (Cmd). The prompt can be configured through the attribute prompt. If the prompt changes as the result of a command processor, the new value is used to query for the next command. 
(Cmd) help

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

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

The help command is built into Cmd. With no arguments, it shows the list of commands available. If you include a command you want help on, the output is more verbose and restricted to details of that command, when available. If we use the greet command, do_greet() is invoked to handle it: 
(Cmd) greet John
Hello John

If your class does not include a specific command processor for a command, the method default() is called with the entire input line as an argument. The built-in implementation of default() reports an error. 
(Cmd) foo
*** Unknown syntax: foo

Since do_EOF() returns True, typing Ctrl-D will drop us out of the interpreter. 
(Cmd) Bye! # Enter Ctrl+D

Notice that no newline is printed, so the results are a little messy. 

Command Arguments 
This version of the example includes a few enhancements to eliminate some of the annoyances and add help for the greet command. 
- cmd_arguments.py 
  1. #!/usr/bin/env python  
  2. import cmd  
  3.   
  4. class HelloWorld(cmd.Cmd):  
  5.     """ Simple command processor example. """  
  6.     def do_greet(self, person):  
  7.         '''greet [person]  
  8.         Greet the named person'''  
  9.         if person:  
  10.             print "Hi, {}".format(person)  
  11.         else:  
  12.             print "Hi!"  
  13.   
  14.     def do_EOF(self, line):  
  15.         print("Bye!")  
  16.         return True  
  17.   
  18.     def do_exit(self, *args):  
  19.         print("See u!")  
  20.         return True  
  21.   
  22.     def postloop(self):  
  23.         print  
  24.   
  25. if __name__ == '__main__':  
  26.     HelloWorld().cmdloop()  
First, let’s look at the help. The docstring added to do_greet() becomes the help text for the command: 
# python cmd_arguments.py
(Cmd) help

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

Undocumented commands:
======================
EOF exit


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

The output shows one optional argument to the greet command, person. Although the argument is optional to the command, there is a distinction between the command and the callback method. The method always takes the argument, but sometimes the value is an empty string. It is left up to the command processor to determine if an empty argument is valid, or do any further parsing and processing of the command. In this example, if a person’s name is provided then the greeting is personalized. 
(Cmd) greet John
Hi, John
(Cmd) greet
Hi!
(Cmd) exit
See u! # Back to console

Whether an argument is given by the user or not, the value passed to the command processor does not include the command itself. That simplifies parsing in the command processor, if multiple arguments are needed. 

Live Help 
In the previous example, the formatting of the help text leaves something to be desired. Since it comes from the docstring, it retains the indentation from our source. We could edit the source to remove the extra white-space, but that would leave our application looking poorly formatted. An alternative solution is to implement a help handler for the greet command, named help_greet(). When present, the help handler is called on to produce help text for the named command. 
- cmd_do_help.py 
  1. import cmd  
  2.   
  3. class HelloWorld(cmd.Cmd):  
  4.     """Simple command processor example."""  
  5.       
  6.     def do_greet(self, person):  
  7.         if person:  
  8.             print "hi,", person  
  9.         else:  
  10.             print 'hi'  
  11.       
  12.     def help_greet(self):  
  13.         print '\n'.join([ 'greet [person]',  
  14.                            'Greet the named person',  
  15.                            ])  
  16.       
  17.     def do_EOF(self, line):  
  18.         return True  
  19.   
  20. if __name__ == '__main__':  
  21.     HelloWorld().cmdloop()  
In this simple example, the text is static but formatted more nicely. It would also be possible to use previous command state to tailor the contents of the help text to the current context. 
$ python cmd_do_help.py
(Cmd) help greet
greet [person]
Greet the named person

It is up to the help handler to actually output the help message, and not simply return the help text for handling elsewhere. 

Auto-Completion 
Cmd includes support for command completion based on the names of the commands with processor methods. The user triggers completion by hitting the tab key at an input prompt. When multiple completions are possible, pressing tab twice prints a list of the options
$ python cmd_do_help.py
(Cmd) 
EOF greet help
(Cmd) h
(Cmd) help

Once the command is known, argument completion is handled by methods with the prefix complete_. This allows you to assemble a list of possible completions using your own criteria (query a database, look at at a file or directory on the filesystem, etc.). In this case, the program has a hard-coded set of “friends” who receive a less formal greeting than named or anonymous strangers. A real program would probably save the list somewhere, and either read it once and cache the contents to be scanned as needed. 
- cmd_arg_completion.py 
  1. import cmd  
  2.   
  3. class HelloWorld(cmd.Cmd):  
  4.     """Simple command processor example."""  
  5.       
  6.     FRIENDS = [ 'Alice''Adam''Barbara''Bob' ]  
  7.       
  8.     def do_greet(self, person):  
  9.         "Greet the person"  
  10.         if person and person in self.FRIENDS:  
  11.             greeting = 'hi, %s!' % person  
  12.         elif person:  
  13.             greeting = "hello, " + person  
  14.         else:  
  15.             greeting = 'hello'  
  16.         print greeting  
  17.       
  18.     def complete_greet(self, text, line, begidx, endidx):  
  19.         if not text:  
  20.             completions = self.FRIENDS[:]  
  21.         else:  
  22.             completions = [ f  
  23.                             for f in self.FRIENDS  
  24.                             if f.startswith(text)  
  25.                             ]  
  26.         return completions  
  27.       
  28.     def do_EOF(self, line):  
  29.         return True  
  30.   
  31. if __name__ == '__main__':  
  32.     HelloWorld().cmdloop()  
When there is input text, complete_greet() returns a list of friends that match. Otherwise, the full list of friends is returned. 
$ python cmd_arg_completion.py
(Cmd) greet 
Adam Alice Barbara Bob
(Cmd) greet A
Adam Alice
(Cmd) greet Ad
(Cmd) greet Adam
hi, Adam!


Overriding Base Class Methods 
Cmd includes several methods that can be overridden as hooks for taking actions or altering the base class behavior. This example is not exhaustive, but contains many of the methods commonly useful. 
- cmd_illustrate_methods.py 
  1. import cmd  
  2.   
  3. class Illustrate(cmd.Cmd):  
  4.     "Illustrate the base class method use."  
  5.       
  6.     def cmdloop(self, intro=None):  
  7.         print 'cmdloop(%s)' % intro  
  8.         return cmd.Cmd.cmdloop(self, intro)  
  9.       
  10.     def preloop(self):  
  11.         print 'preloop()'  
  12.       
  13.     def postloop(self):  
  14.         print 'postloop()'  
  15.           
  16.     def parseline(self, line):  
  17.         print 'parseline(%s) =>' % line,  
  18.         ret = cmd.Cmd.parseline(self, line)  
  19.         print ret  
  20.         return ret  
  21.       
  22.     def onecmd(self, s):  
  23.         print 'onecmd(%s)' % s  
  24.         return cmd.Cmd.onecmd(self, s)  
  25.   
  26.     def emptyline(self):  
  27.         print 'emptyline()'  
  28.         return cmd.Cmd.emptyline(self)  
  29.       
  30.     def default(self, line):  
  31.         print 'default(%s)' % line  
  32.         return cmd.Cmd.default(self, line)  
  33.       
  34.     def precmd(self, line):  
  35.         print 'precmd(%s)' % line  
  36.         return cmd.Cmd.precmd(self, line)  
  37.       
  38.     def postcmd(self, stop, line):  
  39.         print 'postcmd(%s, %s)' % (stop, line)  
  40.         return cmd.Cmd.postcmd(self, stop, line)  
  41.       
  42.     def do_greet(self, line):  
  43.         print 'hello,', line  
  44.   
  45.     def do_EOF(self, line):  
  46.         "Exit"  
  47.         return True  
  48.   
  49. if __name__ == '__main__':  
  50.     Illustrate().cmdloop('Illustrating the methods of cmd.Cmd')  
cmdloop() is the main processing loop of the interpreter. You can override it, but it is usually not necessary, since the preloop() and postloop() hooks are available. 

Each iteration through cmdloop() calls onecmd() to dispatch the command to its processor. The actual input line is parsed with parseline() to create a tuple containing the command, and the remaining portion of the line. 

If the line is empty, emptyline() is called. The default implementation runs the previous command again. If the line contains a command, first precmd() is called then the processor is looked up and invoked. If none is found, default() is called instead. Finally postcmd() is called. 

Here’s an example session with print statements added: 
$ python cmd_illustrate_methods.py
cmdloop(Illustrating the methods of cmd.Cmd)
preloop()
Illustrating the methods of cmd.Cmd

(Cmd) greet Bob
precmd(greet Bob)
onecmd(greet Bob)
parseline(greet Bob) => ('greet', 'Bob', 'greet Bob')
hello, Bob
postcmd(None, greet Bob)

(Cmd) ^Dprecmd(EOF)
onecmd(EOF)
parseline(EOF) => ('EOF', '', 'EOF')
postcmd(True, EOF)
postloop()

Configuring Cmd Through Attributes 
In addition to the methods described above, there are several attributes for controlling command interpreters. prompt can be set to a string to be printed each time the user is asked for a new command; intro is the “welcome” message printed at the start of the program. cmdloop() takes an argument for this value, or you can set it on the class directly. 

When printing help, the doc_headermisc_headerundoc_header, and ruler attributes are used to format the output. 

This example class shows a command processor to let the user control the prompt for the interactive session. 
- cmd_attributes.py 
  1. import cmd  
  2.   
  3. class HelloWorld(cmd.Cmd):  
  4.     """Simple command processor example."""  
  5.   
  6.     prompt = 'prompt: '  
  7.     intro = "Simple command processor example."  
  8.   
  9.     doc_header = 'doc_header'  
  10.     misc_header = 'misc_header'  
  11.     undoc_header = 'undoc_header'  
  12.       
  13.     ruler = '-'  
  14.       
  15.     def do_prompt(self, line):  
  16.         "Change the interactive prompt"  
  17.         self.prompt = line + ': '  
  18.   
  19.     def do_EOF(self, line):  
  20.         return True  
  21.   
  22. if __name__ == '__main__':  
  23.     HelloWorld().cmdloop()  
The demonstration: 
$ python cmd_attributes.py
Simple command processor example.
prompt: prompt hello
hello: help

doc_header
----------
prompt

undoc_header
------------
EOF help

hello:

Shelling Out 
To supplement the standard command processing, Cmd includes 2 special command prefixes. A question mark (?) is equivalent to the built-in help command, and can be used in the same way. An exclamation point (!) maps to do_shell(), and is intended for shelling out to run other commands, as in this example. 
- cmd_do_shell.py 
  1. import cmd  
  2. import os  
  3.   
  4. class ShellEnabled(cmd.Cmd):  
  5.       
  6.     last_output = ''  
  7.   
  8.     def do_shell(self, line):  
  9.         "Run a shell command"  
  10.         print "running shell command:", line  
  11.         output = os.popen(line).read()  
  12.         print output  
  13.         self.last_output = output  
  14.       
  15.     def do_echo(self, line):  
  16.         "Print the input, replacing '$out' with the output of the last shell command"  
  17.         # Obviously not robust  
  18.         print line.replace('$out', self.last_output)  
  19.       
  20.     def do_EOF(self, line):  
  21.         return True  
  22.       
  23. if __name__ == '__main__':  
  24.     ShellEnabled().cmdloop()  
Demonstration: 
$ python cmd_do_shell.py
(Cmd) ?

Documented commands (type help ):
========================================
echo shell

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


(Cmd) ? shell
Run a shell command
(Cmd) ? echo
Print the input, replacing '$out' with the output of the last shell command
(Cmd) shell pwd
running shell command: pwd
/Users/dhellmann/Documents/PyMOTW/in_progress/cmd


(Cmd) ! pwd
running shell command: pwd
/Users/dhellmann/Documents/PyMOTW/in_progress/cmd


(Cmd) echo $out
/Users/dhellmann/Documents/PyMOTW/in_progress/cmd


Alternative Inputs 
While the default mode for Cmd() is to interact with the user through the readline library, it is also possible to pass a series of commands in to standard input using standard Unix shell redirection: 
$ echo help | python cmd_do_help.py
(Cmd)
Documented commands (type help ):
========================================
greet

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

If you would rather have your program read the script file directly, a few other changes may be needed. Since readline interacts with the terminal/tty device, rather than the standard input stream, you should disable it if you know your script is going to be reading from a file. Also, to avoid printing superfluous prompts, you can set the prompt to an empty string. This example shows how to open a file and pass it as input to a modified version of the HelloWorld example. 
- cmd_file.py 
  1. import cmd  
  2.   
  3. class HelloWorld(cmd.Cmd):  
  4.     """Simple command processor example."""  
  5.       
  6.     # Disable rawinput module use  
  7.     use_rawinput = False  
  8.       
  9.     # Do not show a prompt after each command read  
  10.     prompt = ''  
  11.       
  12.     def do_greet(self, line):  
  13.         print "hello,", line  
  14.       
  15.     def do_EOF(self, line):  
  16.         return True  
  17.   
  18. if __name__ == '__main__':  
  19.     import sys  
  20.     input = open(sys.argv[1], 'rt')  
  21.     try:  
  22.         HelloWorld(stdin=input).cmdloop()  
  23.     finally:  
  24.         input.close()  
With use_rawinput set to False and prompt set to an empty string, we can call the script on this input file: 
- cmd_file.txt 
  1. greet  
  2. greet Alice and Bob  
to produce output like: 
$ python cmd_file.py cmd_file.txt
hello,
hello, Alice and Bob

Commands from sys.argv 
You can also process command line arguments to the program as a command for your interpreter class, instead of reading commands from stdin or a file. To use the command line arguments, you can call onecmd() directly, as in this example. 
- cmd_argv.py 
  1. import cmd  
  2.   
  3. class InteractiveOrCommandLine(cmd.Cmd):  
  4.     """Accepts commands via the normal interactive prompt or on the command line."""  
  5.   
  6.     def do_greet(self, line):  
  7.         print 'hello,', line  
  8.       
  9.     def do_EOF(self, line):  
  10.         return True  
  11.   
  12. if __name__ == '__main__':  
  13.     import sys  
  14.     if len(sys.argv) > 1:  
  15.         InteractiveOrCommandLine().onecmd(' '.join(sys.argv[1:]))  
  16.     else:  
  17.         InteractiveOrCommandLine().cmdloop()  
Since onecmd() takes a single string as input, the arguments to the program need to be joined together before being passed in. 
$ python cmd_argv.py greet Command Line User
hello, Command Line User
$ python cmd_argv.py
(Cmd) greet Interactive User
hello, Interactive User


Supplement 
FAQ - How to exit the cmd loop of cmd module cleanly 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...