Text of docs.python.org › uk › 3 › library › cmd.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

cmd — Support for line-oriented command interpreters — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Command-line interface libraries » cmd — Support for line-oriented command interpreters | Theme | cmd — Support for line-oriented command interpreters ¶ Вихідний код: Lib/cmd.py Клас Cmd забезпечує просту структуру для написання рядково-орієнтованих інтерпретаторів команд.

Вони часто корисні для тестових систем, інструментів адміністрування та прототипів, які пізніше будуть загорнуті в більш складний інтерфейс. A command interpreter built with Cmd typically presents the user with an interactive prompt, reads input one line at a time, and dispatches each command to a method named do_ followed by the command name.

For example, the help command is handled by the do_help() method. Apart from the built-in help command, most of the interpreter’s behavior is defined by the do_* methods you add in your own subclass. class cmd. Cmd ( completekey = 'tab' , stdin = None , stdout = None ) ¶ Екземпляр Cmd або екземпляр підкласу — це рядково-орієнтована структура інтерпретатора.

Немає вагомих причин створювати сам Cmd ; скоріше, це корисно як суперклас класу інтерпретатора, який ви визначаєте самостійно, щоб успадкувати методи Cmd та інкапсулювати методи дії. Необов’язковий аргумент completekey є назвою readline ключа завершення; типово Tab .

Якщо completekey не None і readline доступний, завершення команди виконується автоматично. 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.

Необов’язкові аргументи stdin і stdout визначають вхідні та вихідні файлові об’єкти, які екземпляр Cmd або екземпляр підкласу використовуватиме для введення та виведення. Якщо не вказати, за замовчуванням вони будуть sys.stdin і sys.stdout . Якщо ви хочете, щоб використовувався заданий stdin , обов’язково встановіть для атрибута екземпляра use_rawinput значення False , інакше stdin буде проігноровано.

Змінено в версії 3.13: completekey='tab' is replaced by '^I' for editline . 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 ( line ) ¶ 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 line , 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 ) ¶ Метод підхоплення виконується безпосередньо перед інтерпретацією рядка командного рядка, але після створення та видачі підказки введення. Цей метод є заглушкою в Cmd ; він існує, щоб бути заміненим підкласами.

Повернене значення використовується як команда, яка буде виконана методом onecmd() ; реа�

The rest of this page is on the live site.