cmd --- 以列為導向的指令直譯器支援

原始碼:Lib/cmd.py


Cmd 類別提供了一個簡單的架構,用於撰寫行導向的命令直譯器。這類直譯器常用於測試控制工具、管理工具以及日後將包裝於更高階介面的原型中。

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

Cmd 實例或其子類別實例是一種行導向的直譯器架構。通常沒有必要直接實例化 Cmd 本身;它更適合作為你自定義的直譯器類別的父類別,讓你能繼承 Cmd 的方法,並封裝動作方法。

可選引數 completekeyreadline 模組中用於自動完成的按鍵名稱;預設為 Tab。若 completekey 不為 Nonereadline 可用,則會自動啟用命令自動完成功能。

預設值 'tab' 會被特殊處理,使其在所有的 readline.backend 中皆代表 Tab 鍵。具體來說,若 readline.backendeditline,則 Cmd 會改用 '^I' 取代 'tab'。請注意,其他值不會有此處理方式,且可能僅能在特定的後端中適用。

可選引數 stdinstdout 用來指定 Cmd 實例或其子類別實例所使用的輸入與輸出檔案物件。若未指定,預設為 sys.stdinsys.stdout

若你希望使用指定的 stdin,請務必將該實例的 use_rawinput 屬性設為 False,否則 stdin 會被忽略。

在 3.13 版的變更: 對於 editlinecompletekey='tab' 會被替換為 '^I'

Cmd 物件

Cmd 實例具有以下方法:

Cmd.cmdloop(intro=None)

重複顯示提示字元、接收輸入、剖析接收到的輸入字串前綴,並派發給動作方法,將其餘部分作為引數傳遞給它們

此可選引數為橫幅或導言字串,會在首次顯示提示字元前輸出(此值會覆寫 intro 類別屬性)。

如果已載入 readline 模組,輸入行將自動繼承類似 bash 的歷史紀錄編輯功能(例如 Control-P 可向上捲動至上一個指令,Control-N 向下捲動至下一個指令,Control-F 非破壞性地將游標向右移動,Control-B 非破壞性地將游標向左移動等)。

當輸入為檔案結尾(EOF)時,會傳回字串 'EOF'

直譯器實例僅當存在 do_foo() 方法時,才會識別命令名稱 foo。作為特殊情況,以字元 '?' 開頭的行會被派發至 do_help() 方法;另一個特殊情況是,以字元 '!' 開頭的行會被派發至 do_shell() 方法(若該方法已定義)。

postcmd() 方法回傳真值時,此方法將會結束。傳遞給 postcmd()stop 引數是該命令對應的 do_*() 方法的回傳值。

如果啟用了自動完成,命令的自動完成將會自動執行,而命令引數的自動完成則是透過呼叫 complete_foo() 方法並傳入 textlinebegidxendidx 引數來處理。text 是要比對的字串前綴:所有回傳的符合項都必須以此字串開頭。line 是目前的輸入行(前置空白會被移除),begidxendidx 則分別是前綴字串的起始與結束索引,可用來根據引數所在的位置提供不同的自動完成結果。

Cmd.do_help(arg)

所有 Cmd 的子類別都會繼承預先定義的 do_help() 方法。當此方法接收到引數 'bar' 時,會呼叫對應的 help_bar() 方法;若該方法不存在,則會列印 do_bar() 的說明字串(若有的話)。若未提供任何引數,do_help() 會列出所有可用的說明主題(也就是所有具有對應 help_*() 方法或有說明字串的命令),並且也會列出所有尚未記錄的命令。

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. By default, it returns an empty list.

Cmd.columnize(list, displaywidth=80)

Method called to display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces for readability.

Cmd.precmd(line)

Hook method executed just before the command line line is interpreted, but after the input prompt is generated and issued. 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. 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. 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.

Cmd.preloop()

Hook method executed once when cmdloop() is called. This method is a stub in Cmd; it exists to be overridden by subclasses.

Cmd.postloop()

Hook method executed once when cmdloop() is about to return. This method is a stub in Cmd; it exists to be overridden by subclasses.

Instances of Cmd subclasses have some public instance variables:

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.

Cmd.intro

A string to issue as an intro or banner. May be overridden by giving the cmdloop() method an argument.

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

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

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.

This section presents a simple example of how to build a shell around a few of the commands in the turtle module.

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