cmd — Interpréteurs en ligne de commande.

Code source: Lib/cmd.py


La Cmd fournit une base simple permettant d'écrire des interpréteurs en ligne de commande. Ceux-ci sont souvent utiles pour piloter des tests, pour des outils administratifs, et pour des prototypes destinés à être intégrés à une interface plus sophistiquée.

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

Une instance de Cmd ou d'une classe en héritant est un framework orienté ligne de commande. Il n'y a pas de bonne raison d'instancier Cmd directement. Elle est plutôt utile en tant que classe mère d'une classe-interprète que vous définirez afin d'hériter des méthodes de Cmd et d'encapsuler les opérations.

L'argument facultatif completekey est le nom readline d'une touche de complétion. Si completekey ne vaut pas None et que readline est disponible, la complétion de commandes est faite automatiquement.

The default, 'tab', is treated specially, so that it refers to the Tab key on every readline.backend. Specifically, if readline.backend is editline, Cmd will use '^I' instead of 'tab'. Note that other values are not treated this way, and might only work with a specific backend.

Les arguments facultatifs stdin et stdout spécifient les objets-fichiers de lecture et d'écriture que l'instance de Cmd ou d'une classe fille utilisera comme entrée et sortie. Si ces arguments ne sont pas spécifiés, ils prendront comme valeur par défaut sys.stdin et sys.stdout.

Si vous souhaitez qu'un stdin donné soit utilisé, assurez-vous que l'attribut use_rawinput de l'instance vaille False, faute de quoi stdin sera ignoré.

Modifié dans la version 3.13: completekey='tab' is replaced by '^I' for editline.

Objets Cmd

Une instance de Cmd possède les méthodes suivantes :

Cmd.cmdloop(intro=None)

Affiche une invite de commande de manière répétée, accepte une entrée, soustrait un préfixe initial de l'entrée reçue et envoie aux méthodes d'opération la partie restante de l'entrée reçue.

L'argument facultatif est une bannière ou chaîne de caractères d'introduction à afficher avant la première invite de commande (il redéfinit l'attribut de classe intro).

Si le module readline est chargé, l'entrée héritera automatiquement d'une édition d'historique similaire à bash (Par exemple, Control-P reviendra à la dernière commande, Control-N avancera à la suivante, Control-F déplace le curseur vers la droite, Control-B déplace le curseur vers la gauche, etc...).

Une caractère de fin de fichier est transmis via la chaîne de caractères '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()

Méthode appelée quand une ligne vide est entrée en réponse à l'invite de commande. Si cette méthode n'est pas surchargée, elle répète la dernière commande non-vide entrée.

Cmd.default(line)

Méthode appelée lorsque le préfixe de commande d'une ligne entrée n'est pas reconnu. Si cette méthode n'est pas surchargée, elle affiche un message d'erreur et s'arrête.

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)

Méthode appelée pour afficher une liste de chaînes de caractères sous la forme d'un ensemble compact de colonnes. Chaque colonne est de largeur minimale. Les colonnes sont séparées par deux espaces pour faciliter la lecture.

Cmd.precmd(line)

Méthode de rappel exécutée juste avant que la ligne de commande line ne soit interprétée, mais après que l'invite de commande ait été généré et affiché. Cette méthode existe afin d'être surchargée par des classes filles de Cmd. La valeur de retour est utilisée comme la commande qui sera exécutée par la méthode onecmd(). L'implémentation de precmd() peut réécrire la commande ou simplement renvoyer line sans modification.

Cmd.postcmd(stop, line)

Méthode de rappel exécutée juste après qu'une commande ait été exécutée. Cette méthode existe afin d'être surchargée par des classes filles de Cmd. line est la ligne de commande ayant été exécutée et stop est un flag indiquant si l'exécution sera terminée après un appel à postcmd(). stop sera la valeur de retour de onecmd(). La valeur de retour de cette méthode sera utilisée comme nouvelle valeur pour le flag interne correspondant à stop. Renvoyer False permettra à l'interprétation de continuer.

Cmd.preloop()

Méthode de rappel exécutée une fois lorsque cmdloop() est appelée. Cette méthode existe afin d'être surchargée par des classes filles de Cmd.

Cmd.postloop()

Méthode de rappel exécutée une fois lorsque cmdloop() va s'arrêter. Cette méthode existe afin d'être surchargée par des classes filles de Cmd.

Les instances de classes filles de Cmd possèdent des variables d'instance publiques :

Cmd.prompt

L'invite de commande affiché pour solliciter une entrée.

Cmd.identchars

La chaîne de caractères acceptée en tant que préfixe de commande.

Cmd.lastcmd

Le dernier préfixe de commande non-vide vu.

Cmd.cmdqueue

Une liste de lignes entrées en file. La liste cmdqueue est vérifiée dans cmdloop() lorsqu'une nouvelle entrée est nécessitée; si elle n'est pas vide, ses éléments seront traités dans l'ordre, comme si ils avaient entrés dans l'invite de commande.

Cmd.intro

Une chaîne de caractères à afficher en introduction ou bannière. Peut être surchargée en passant un argument à la méthode cmdloop().

Cmd.doc_header

L'en-tête à afficher si la sortie de l'aide possède une section pour les commandes documentées.

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

Le caractère utilisé pour afficher des lignes de séparation sous les en-têtes de messages d'aide. Si il est vide, aucune ligne de séparation n'est affichée. Par défaut, ce caractère vaut '='.

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

Exemple

Le module cmd est utile pour produire des invites de commande permettant à l'utilisateur de travailler avec un programme de manière interactive.

Cette section présente un exemple simple de comment produire une invite de commande autour de quelques commandes du module 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()

Voici une session d'exemple avec l'invite de commande turtle. Elle montre les fonctions d'aide, utilise les lignes vides pour répéter des commandes et montre l'utilitaire de playback :

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