cmd --- 行指向のコマンドインタープリタのサポート

ソースコード: Lib/cmd.py


Cmd クラスでは、行指向のコマンドインタープリタを書くための簡単なフレームワークを提供します。テストハーネスや管理ツール、そして、後により洗練されたインターフェイスでラップするプロトタイプとして、こうしたインタープリタはよく役に立ちます。

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

Cmd インスタンス、あるいはサブクラスのインスタンスは、行指向のインタープリタ・フレームワークです。 Cmd 自身をインスタンス化することはありません。むしろ、 Cmd のメソッドを継承したり、アクションメソッドをカプセル化するために、あなたが自分で定義するインタープリタクラスのスーパークラスとしての便利です。

オプション引数 completekey は、補完キーの readline 名です。デフォルトは Tab です。 completekeyNone でなく、 readline が利用できるならば、コマンド補完は自動的に行われます。

オプション引数の stdinstdout には、Cmd またはそのサブクラスのインスタンスが入出力に使用するファイルオブジェクトを指定します。省略時には sys.stdinsys.stdout が使用されます。

引数に渡した stdin を使いたい場合は、インスタンスの use_rawinput 属性を False にセットしてください。そうしないと stdin は無視されます。

Cmdオブジェクト

Cmd インスタンスは、次のメソッドを持ちます:

Cmd.cmdloop(intro=None)

プロンプトを繰り返し出力し、入力を受け取り、受け取った入力から取り去った先頭の語を解析し、その行の残りを引数としてアクションメソッドへディスパッチします。

オプションの引数は、最初のプロンプトの前に表示されるバナーあるいはイントロ用の文字列です (これはクラス属性 intro をオーバーライドします)。

readline モジュールがロードされているなら、入力は自動的に bash のような履歴リスト編集機能を受け継ぎます(例えば、 Control-P は直前のコマンドへのスクロールバック、 Control-N は次のものへ進む、 Control-F はカーソルを右へ非破壊的に進める、 Control-B はカーソルを非破壊的に左へ移動させる等)。

入力のファイル終端は、文字列 '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.

Cmd.do_help(arg)

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

プロンプトに空行が入力されたときに呼び出されるメソッド。このメソッドがオーバーライドされていないなら、最後に入力された空行でないコマンドが繰り返されます。

Cmd.default(line)

コマンドの先頭の語が認識されないときに、入力行に対して呼び出されます。このメソッドがオーバーライドされていないなら、エラーメッセージを表示して戻ります。

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)

コマンド行 line が解釈実行される直前、しかし入力プロンプトが作られ表示された後に実行されるフックメソッド。このメソッドは Cmd 内のスタブであって、サブクラスでオーバーライドされるために存在します。戻り値は onecmd() メソッドが実行するコマンドとして使われます。 precmd() の実装では、コマンドを書き換えるかもしれないし、あるいは単に変更していない line を返すかもしれません。

Cmd.postcmd(stop, line)

コマンドディスパッチが終わった直後に実行されるフックメソッド。このメソッドは Cmd 内のスタブで、サブクラスでオーバーライドされるために存在します。 line は実行されたコマンド行で、 stoppostcmd() の呼び出しの後に実行を停止するかどうかを示すフラグです。これは onecmd() メソッドの戻り値です。このメソッドの戻り値は、 stop に対応する内部フラグの新しい値として使われます。偽を返すと、実行を続けます。

Cmd.preloop()

cmdloop() が呼び出されたときに一度だけ実行されるフックメソッド。このメソッドは Cmd 内のスタブであって、サブクラスでオーバーライドされるために存在します。

Cmd.postloop()

cmdloop() が戻る直前に一度だけ実行されるフックメソッド。このメソッドは Cmd 内のスタブであって、サブクラスでオーバーライドされるために存在します。

Cmd のサブクラスのインスタンスは、公開されたインスタンス変数をいくつか持っています:

Cmd.prompt

入力を求めるために表示されるプロンプト。

Cmd.identchars

コマンドの先頭の語として受け入れられる文字の文字列。

Cmd.lastcmd

最後の空でないコマンド接頭辞。

Cmd.cmdqueue

キューに入れられた入力行のリスト。cmdqueue リストは新たな入力が必要な際に cmdloop() 内でチェックされます; これが空でない場合、その要素は、あたかもプロンプトから入力されたかのように順に処理されます。

Cmd.intro

イントロあるいはバナーとして表示される文字列。 cmdloop() メソッドに引数を与えるために、オーバーライドされるかもしれません。

Cmd.doc_header

ヘルプ出力に文書化されたコマンドのセクションがある場合に表示するヘッダ。

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

ヘルプメッセージのヘッダの下に、区切り行を表示するために使われる文字。空のときは、ルーラ行が表示されません。デフォルトでは、'=' です。

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 の例

cmd モジュールは、ユーザーがプログラムと対話的に連携できるカスタムシェルを構築するのに主に役立ちます。

この節では、turtle モジュールのいくつかのコマンドを持ったシェルの作成方法の簡単な例を示します。

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

以下は、turtle シェルでの機能のヘルプ表示、空行によるコマンドの繰り返し、単純な記録と再実行のセッション例です:

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