Skip to content

# Miscellaneous Features

## Timer

Turn the timer setting on, and `cmd2` will show the wall time it takes for each command to execute.

## Exiting

Like many shell applications, `cmd2` applications can be exited by pressing `Ctrl-D` on an empty line, or by executing the `quit` command.

## select

Presents numbered options to user, as bash `select`.

`app.select` is called from within a method (not by the user directly; it is `app.select`, not `app.do_select`).

## `` cmd2.Cmd.select

    select(opts, prompt='Your choice? ')

Present a numbered menu to the user.

Modeled after the bash shell's SELECT. Returns the item chosen.

Argument `opts` can be:

| a single string -> will be split into one-word options | a list of strings -> will be offered as options | a list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user

Source code in `cmd2/cmd2.py`

    4473
    4474
    4475
    4476
    4477
    4478
    4479
    4480
    4481
    4482
    4483
    4484
    4485
    4486
    4487
    4488
    4489
    4490
    4491
    4492
    4493
    4494
    4495
    4496
    4497
    4498
    4499
    4500
    4501
    4502
    4503
    4504
    4505
    4506
    4507
    4508
    4509
    4510
    4511
    4512
    4513
    4514
    4515
    4516
    4517
    4518
    4519
    4520
    4521
    4522

    def select(self, opts: str | list[str] | list[tuple[Any, str | None]], prompt: str = 'Your choice? ') -> Any:
        """Present a numbered menu to the user.

        Modeled after the bash shell's SELECT.  Returns the item chosen.

        Argument ``opts`` can be:

          | a single string -> will be split into one-word options
          | a list of strings -> will be offered as options
          | a list of tuples -> interpreted as (value, text), so
                                that the return value can differ from
                                the text advertised to the user
        """
        local_opts: list[str] | list[tuple[Any, str | None]]
        if isinstance(opts, str):
            local_opts = cast(list[tuple[Any, str | None]], list(zip(opts.split(), opts.split(), strict=False)))
        else:
            local_opts = opts
        fulloptions: list[tuple[Any, str | None]] = []
        for opt in local_opts:
            if isinstance(opt, str):
                fulloptions.append((opt, opt))
            else:
                try:
                    fulloptions.append((opt[0], opt[1]))
                except IndexError:
                    fulloptions.append((opt[0], opt[0]))
        for idx, (_, text) in enumerate(fulloptions):
            self.poutput('  %2d. %s' % (idx + 1, text))  # noqa: UP031

        while True:
            try:
                response = self.read_input(prompt)
            except EOFError:
                response = ''
                self.poutput()
            except KeyboardInterrupt:
                self.poutput('^C')
                raise

            if not response:
                continue

            try:
                choice = int(response)
                if choice < 1:
                    raise IndexError  # noqa: TRY301
                return fulloptions[choice - 1][0]
            except (ValueError, IndexError):
                self.poutput(f"'{response}' isn't a valid choice. Pick a number between 1 and {len(fulloptions)}:")

    def do_eat(self, arg):
        sauce = self.select('sweet salty', 'Sauce? ')
        result = '{food} with {sauce} sauce, yum!'
        result = result.format(food=arg, sauce=sauce)
        self.stdout.write(result + '\n')

    (Cmd) eat wheaties
        1. sweet
        2. salty
    Sauce? 2
    wheaties with salty sauce, yum!

## Disabling Commands

`cmd2` supports disabling commands during runtime. This is useful if certain commands should only be available when the application is in a specific state. When a command is disabled, it will not show up in the help menu or tab complete. If a user tries to run the command, a command-specific message supplied by the developer will be printed. The following functions support this feature.

- enable_command : Enable an individual command
- enable_category : Enable an entire category of commands
- disable_command : Disable an individual command and set the message that will print when this command is run or help is called on it while disabled
- disable_category : Disable an entire category of commands and set the message that will print when anything in this category is run or help is called on it while disabled

See the definitions of these functions for descriptions of their arguments.

See the `do_enable_commands()` and `do_disable_commands()` functions in the help_categories.py example for a demonstration.

## Default to shell

Every `cmd2` application can execute operating-system level (shell) commands with `shell` or a `!` shortcut:

    (Cmd) shell which python
    /usr/bin/python
    (Cmd) !which python
    /usr/bin/python

However, if the parameter `default_to_shell` is `True`, then every thing entered which doesn't match another command will be attempted on the operating system. Only if that attempt fails (i.e., produces a nonzero return value) will the application's own `default` method be called.

    (Cmd) which python
    /usr/bin/python
    (Cmd) my dog has fleas
    sh: my: not found
    *** Unknown syntax: my dog has fleas