cmd — Suporte para interpretadores de comando orientado a linhas

Código-fonte: Lib/cmd.py


A classe Cmd fornece um framework simples para escrever interpretadores de comando orientados a linhas. Eles são frequentemente úteis para melhorar testes, ferramentas administrativas e protótipos que mais tarde serão encapsulados em uma interface mais sofisticada.

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

Uma instância de Cmd ou instância de sua subclasse é um framework de interpretador orientado a linhas. Não há um bom motivo para instanciar Cmd em si; em vez disso, ele é útil como uma superclasse de uma classe de interpretador que você mesmo define para herdar os métodos de Cmd e encapsular métodos de ação.

O argumento opcional completekey é o nome readline de uma chave de conclusão; o padrão é Tab. Se completekey não for None e readline estiver disponível, a conclusão do comando será feita automaticamente.

Os argumentos opcionais stdin e stdout especificam os objetos arquivo de entrada e saída que a instância Cmd ou instância de sua subclasse usará para entrada e saída. Se não forem especificados, eles serão padronizados para sys.stdin e sys.stdout.

Se você quiser que um determinado stdin seja usado, certifique-se de definir o atributo use_rawinput da instância como False, caso contrário, stdin será ignorado.

Objetos Cmd

Uma instância Cmd tem os seguintes métodos:

Cmd.cmdloop(intro=None)

Emite um prompt repetidamente, aceite a entrada, analise um prefixo inicial da entrada recebida e despache para métodos de ação, passando a eles o restante da linha como argumento.

O argumento opcional é um banner ou uma string de introdução a ser emitida antes do primeiro prompt (isso substitui o atributo de classe intro).

Se o módulo readline for carregado, a entrada vai herdar automaticamente a edição de lista de histórico semelhante a bash (por exemplo, Control-P retorna ao último comando, Control-N avança para o próximo, Control-F move o cursor para a direita de forma não destrutiva, Control-B move o cursor para a esquerda de forma não destrutiva, etc.).

Um fim de arquivo na entrada é retornado como a 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()

Método chamado quando uma linha vazia é inserida em resposta ao prompt. Se esse método não for substituído, ele repete o último comando não vazio inserido.

Cmd.default(line)

Método chamado em uma linha de entrada quando o prefixo do comando não é reconhecido. Se esse método não for substituído, ele imprime uma mensagem de erro e retorna.

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.precmd(line)

Método gancho executado logo antes da linha de comando line ser interpretada, mas depois que o prompt de entrada é gerado e emitido. Este método é um stub em Cmd; ele existe para ser substituído por subclasses. O valor de retorno é usado como o comando que será executado pelo método onecmd(); a implementação precmd() pode reescrever o comando ou simplesmente retornar line inalterado.

Cmd.postcmd(stop, line)

Método gancho executado logo após o término do despacho de um comando. Este método é um stub em Cmd; ele existe para ser substituído por subclasses. line é a linha de comando que foi executada, e stop é um sinalizador que indica se a execução será encerrada após a chamada para postcmd(); este será o valor de retorno do método onecmd(). O valor de retorno deste método será usado como o novo valor para o sinalizador interno que corresponde a stop; retornar false fará com que a interpretação continue.

Cmd.preloop()

Método gancho executado uma vez quando cmdloop() é chamado. Este método é um stub em Cmd; ele existe para ser substituído por subclasses.

Cmd.postloop()

Método gancho executado uma vez quando cmdloop() está para ser retornado. Este método é um stub em Cmd; ele existe para ser substituído por subclasses.

Instâncias das subclasses Cmd têm algumas variáveis de instância públicas:

Cmd.prompt

O prompt emitido para solicitar informações.

Cmd.identchars

A sequência de caracteres aceita para o prefixo do comando.

Cmd.lastcmd

O último prefixo de comando não vazio visto.

Cmd.cmdqueue

Uma lista de linhas de entrada enfileiradas. A lista cmdqueue é verificada em cmdloop() quando uma nova entrada é necessária; se não estiver vazia, seus elementos serão processados em ordem, como se tivessem sido inseridos no prompt.

Cmd.intro

Uma string para emitir como uma introdução ou banner. Pode ser substituída dando ao método cmdloop() um argumento.

Cmd.doc_header

O cabeçalho a ser emitido se a saída de ajuda tiver uma seção para comandos documentados.

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

O caractere usado para desenhar linhas separadoras sob os cabeçalhos de mensagem de ajuda. Se estiver vazio, nenhuma linha de régua será desenhada. O padrão é '='.

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

Exemplo do Cmd

O módulo cmd é útil principalmente para criar shells personalizados que permitem ao usuário trabalhar com um programa interativamente.

Esta seção apresenta um exemplo simples de como construir um shell em torno de alguns dos comandos do módulo 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()

Aqui está uma sessão de exemplo com o shell do turtle mostrando as funções de ajuda, usando linhas em branco para repetir comandos e o recurso simples de gravação e reprodução:

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