cmdSupport for line-oriented command interpreters支持面向行的命令解释器

Source code: Lib/cmd.py


The Cmd class provides a simple framework for writing line-oriented command interpreters. Cmd类为编写面向行的命令解释器提供了一个简单的框架。These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.这些工具通常对测试工具、管理工具和原型非常有用,这些工具和原型稍后将封装在更复杂的界面中。

classcmd.Cmd(completekey='tab', stdin=None, stdout=None)

A Cmd instance or subclass instance is a line-oriented interpreter framework. Cmd实例或子类实例是面向行的解释器框架。There is no good reason to instantiate Cmd itself; rather, it’s useful as a superclass of an interpreter class you define yourself in order to inherit Cmd’s methods and encapsulate action methods.没有很好的理由实例化Cmd本身;相反,它是一个有用的解释器类的超类,您可以自己定义,以继承Cmd的方法并封装动作方法。

The optional argument completekey is the readline name of a completion key; it defaults to Tab. If completekey is not None and readline is available, command completion is done automatically.

The optional arguments stdin and stdout specify the input and output file objects that the Cmd instance or subclass instance will use for input and output. 可选参数stdinstdout指定Cmd实例或子类实例将用于输入和输出的输入和输出文件对象。If not specified, they will default to sys.stdin and sys.stdout.如果未指定,它们将默认为sys.stdinsys.stdout

If you want a given stdin to be used, make sure to set the instance’s use_rawinput attribute to False, otherwise stdin will be ignored.

Cmd Objects对象

A Cmd instance has the following methods:Cmd实例具有以下方法:

Cmd.cmdloop(intro=None)

Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.重复发出提示,接受输入,解析接收到的输入的初始前缀,并分派给操作方法,将行的其余部分作为参数传递给它们。

The optional argument is a banner or intro string to be issued before the first prompt (this overrides the intro class attribute).可选参数是在第一个提示之前发出的横幅或介绍字符串(这将覆盖intro类属性)。

If the readline module is loaded, input will automatically inherit bash-like history-list editing (e.g. Control-P scrolls back to the last command, Control-N forward to the next one, Control-F moves the cursor to the right non-destructively, Control-B moves the cursor to the left non-destructively, etc.).

An end-of-file on input is passed back as the string 'EOF'.

An interpreter instance will recognize a command name foo if and only if it has a method do_foo(). As a special case, a line beginning with the character '?' is dispatched to the method do_help(). As another special case, a line beginning with the character '!' is dispatched to the method do_shell() (if such a method is defined).

This method will return when the postcmd() method returns a true value. The stop argument to postcmd() is the return value from the command’s corresponding do_*() method.

If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, and endidx. text is the string prefix we are attempting to match: all returned matches must begin with it. line is the current input line with leading whitespace removed, begidx and endidx are the beginning and ending indexes of the prefix text, which could be used to provide different completion depending upon which position the argument is in.

All subclasses of Cmd inherit a predefined do_help(). This method, called with an argument 'bar', invokes the corresponding method help_bar(), and if that is not present, prints the docstring of do_bar(), if available. With no argument, do_help() lists all available help topics (that is, all commands with corresponding help_*() methods or commands that have docstrings), and also lists any undocumented commands.

Cmd.onecmd(str)

Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. If there is a do_*() method for the command str, the return value of that method is returned, otherwise the return value from the default() method is returned.

Cmd.emptyline()

Method called when an empty line is entered in response to the prompt. 方法在响应提示输入空行时调用。If this method is not overridden, it repeats the last nonempty command entered.如果此方法未被重写,它将重复输入的最后一个非空命令。

Cmd.default(line)

Method called on an input line when the command prefix is not recognized. 当无法识别命令前缀时,在输入行上调用方法。If this method is not overridden, it prints an error message and returns.如果未重写此方法,它将打印一条错误消息并返回。

Cmd.completedefault(text, line, begidx, endidx)

Method called to complete an input line when no command-specific complete_*() method is available. 当没有命令特定的complete_*()方法可用时,调用该方法来完成输入行。By default, it returns an empty list.默认情况下,它返回一个空列表。

Cmd.precmd(line)

Hook method executed just before the command line line is interpreted, but after the input prompt is generated and issued. 钩子方法在解释命令行line之前执行,但在生成并发出输入提示之后执行。This method is a stub in Cmd; it exists to be overridden by subclasses. The return value is used as the command which will be executed by the onecmd() method; the precmd() implementation may re-write the command or simply return line unchanged.

Cmd.postcmd(stop, line)

Hook method executed just after a command dispatch is finished. 钩子方法在命令分派完成后立即执行。This method is a stub in Cmd; it exists to be overridden by subclasses. 此方法是Cmd中的存根;它的存在是为了被子类覆盖。line is the command line which was executed, and stop is a flag which indicates whether execution will be terminated after the call to postcmd(); this will be the return value of the onecmd() method. line是已执行的命令行,stop是一个标志,指示调用postcmd()后是否终止执行;这将是onecmd()方法的返回值。The return value of this method will be used as the new value for the internal flag which corresponds to stop; returning false will cause interpretation to continue.此方法的返回值将用作与stop相对应的内部标志的新值;返回false将导致解释继续。

Cmd.preloop()

Hook method executed once when cmdloop() is called. 调用cmdloop()时,钩子方法执行一次。This method is a stub in Cmd; it exists to be overridden by subclasses.此方法是Cmd中的存根;它的存在是为了被子类覆盖。

Cmd.postloop()

Hook method executed once when cmdloop() is about to return. cmdloop()即将返回时,钩子方法执行一次。This method is a stub in Cmd; it exists to be overridden by subclasses.此方法是Cmd中的存根;它的存在是为了被子类覆盖。

Instances of Cmd subclasses have some public instance variables:Cmd子类的实例有一些公共实例变量:

Cmd.prompt

The prompt issued to solicit input.为请求输入而发出的提示。

Cmd.identchars

The string of characters accepted for the command prefix.为命令前缀接受的字符串。

Cmd.lastcmd

The last nonempty command prefix seen.看到的最后一个非空命令前缀。

Cmd.cmdqueue

A list of queued input lines. 排队输入行的列表。The cmdqueue list is checked in cmdloop() when new input is needed; if it is nonempty, its elements will be processed in order, as if entered at the prompt.当需要新输入时,在cmdloop()中检查cmdqueue列表;如果它是非空的,它的元素将按顺序处理,就像在提示下输入一样。

Cmd.intro

A string to issue as an intro or banner. 作为介绍或横幅发布的字符串。May be overridden by giving the cmdloop() method an argument.可以通过为cmdloop()方法提供参数来重写。

Cmd.doc_header

The header to issue if the help output has a section for documented commands.如果帮助输出包含文档化命令的部分,则要发出的标题。

Cmd.misc_header

The header to issue if the help output has a section for miscellaneous help topics (that is, there are help_*() methods without corresponding do_*() methods).如果帮助输出中有一个用于其他帮助主题的部分(即,有help_*()方法,但没有相应的do_*()方法),则发出的标题。

Cmd.undoc_header

The header to issue if the help output has a section for undocumented commands (that is, there are do_*() methods without corresponding help_*() methods).如果帮助输出有一个用于未记录命令的部分(即,有do_*()方法,但没有相应的help_*()方法),则发出的标题。

Cmd.ruler

The character used to draw separator lines under the help-message headers. 用于在帮助消息标题下绘制分隔线的字符。If empty, no ruler line is drawn. 如果为空,则不绘制标尺线。It defaults to '='.它默认为'='

Cmd.use_rawinput

A flag, defaulting to true. If true, cmdloop() uses input() to display a prompt and read the next command; if false, sys.stdout.write() and sys.stdin.readline() are used. (This means that by importing readline, on systems that support it, the interpreter will automatically support Emacs-like line editing and command-history keystrokes.)

Cmd Example示例

The cmd module is mainly useful for building custom shells that let a user work with a program interactively.cmd模块主要用于构建自定义shell,让用户以交互方式使用程序。

This section presents a simple example of how to build a shell around a few of the commands in the turtle module.本节介绍了如何围绕turtle模块中的几个命令构建shell的简单示例。

Basic turtle commands such as forward() are added to a Cmd subclass with method named do_forward(). The argument is converted to a number and dispatched to the turtle module. The docstring is used in the help utility provided by the shell.

The example also includes a basic record and playback facility implemented with the precmd() method which is responsible for converting the input to lowercase and writing the commands to a file. The do_playback() method reads the file and adds the recorded commands to the cmdqueue for immediate playback:

import cmd, sys
from turtle import *
class TurtleShell(cmd.Cmd):
intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
prompt = '(turtle) '
file = None

# ----- basic turtle commands -----
def do_forward(self, arg):
'Move the turtle forward by the specified distance: FORWARD 10'
forward(*parse(arg))
def do_right(self, arg):
'Turn turtle right by given number of degrees: RIGHT 20'
right(*parse(arg))
def do_left(self, arg):
'Turn turtle left by given number of degrees: LEFT 90'
left(*parse(arg))
def do_goto(self, arg):
'Move turtle to an absolute position with changing orientation. GOTO 100 200'
goto(*parse(arg))
def do_home(self, arg):
'Return turtle to the home position: HOME'
home()
def do_circle(self, arg):
'Draw circle with given radius an options extent and steps: CIRCLE 50'
circle(*parse(arg))
def do_position(self, arg):
'Print the current turtle position: POSITION'
print('Current position is %d %d\n' % position())
def do_heading(self, arg):
'Print the current turtle heading in degrees: HEADING'
print('Current heading is %d\n' % (heading(),))
def do_color(self, arg):
'Set the color: COLOR BLUE'
color(arg.lower())
def do_undo(self, arg):
'Undo (repeatedly) the last turtle action(s): UNDO'
def do_reset(self, arg):
'Clear the screen and return turtle to center: RESET'
reset()
def do_bye(self, arg):
'Stop recording, close the turtle window, and exit: BYE'
print('Thank you for using Turtle')
self.close()
bye()
return True

# ----- record and playback -----
def do_record(self, arg):
'Save future commands to filename: RECORD rose.cmd'
self.file = open(arg, 'w')
def do_playback(self, arg):
'Playback commands from a file: PLAYBACK rose.cmd'
self.close()
with open(arg) as f:
self.cmdqueue.extend(f.read().splitlines())
def precmd(self, line):
line = line.lower()
if self.file and 'playback' not in line:
print(line, file=self.file)
return line
def close(self):
if self.file:
self.file.close()
self.file = None

def parse(arg):
'Convert a series of zero or more numbers to an argument tuple'
return tuple(map(int, arg.split()))

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

Here is a sample session with the turtle shell showing the help functions, using blank lines to repeat commands, and the simple record and playback facility:下面是一个使用龟甲的示例会话,显示了帮助功能,使用空行重复命令,以及简单的记录和播放功能:

Welcome to the turtle shell. Type help or ? to list commands.
(turtle) ?

Documented commands (type help <topic>):
========================================
bye color goto home playback record right
circle forward heading left position reset undo

(turtle) help forward
Move the turtle forward by the specified distance: FORWARD 10
(turtle) record spiral.cmd
(turtle) position
Current position is 0 0

(turtle) heading
Current heading is 0

(turtle) reset
(turtle) circle 20
(turtle) right 30
(turtle) circle 40
(turtle) right 30
(turtle) circle 60
(turtle) right 30
(turtle) circle 80
(turtle) right 30
(turtle) circle 100
(turtle) right 30
(turtle) circle 120
(turtle) right 30
(turtle) circle 120
(turtle) heading
Current heading is 180

(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 500
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 300
(turtle) playback spiral.cmd
Current position is 0 0

Current heading is 0

Current heading is 180

(turtle) bye
Thank you for using Turtle