Skip to content

command

clap.command

command(cls: type[T]) -> type[T]
command(
    *,
    name: str = ...,
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    usage: Optional[str] = ...,
    about: Optional[str] = ...,
    long_about: Optional[str] = ...,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = ...,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = ...,
    subcommand_help_heading: str = ...,
    subcommand_value_name: str = ...,
    color: ColorChoice = Auto,
    help_styles: Optional[Styles] = ...,
    help_template: Optional[str] = ...,
    max_term_width: Optional[int] = ...,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: str = ...,
    allow_abbrev: bool = True,
    exit_on_error: bool = True,
) -> Callable[[type[T]], type[T]]
command(
    cls: Optional[type[T]] = None,
    /,
    *,
    name: str = basename(argv[0]),
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    usage: Optional[str] = None,
    about: Optional[str] = None,
    long_about: Optional[str] = None,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = None,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = None,
    subcommand_help_heading: str = "Commands",
    subcommand_value_name: str = "COMMAND",
    color: Optional[ColorChoice] = None,
    styles: Optional[Styles] = None,
    help_template: Optional[str] = None,
    max_term_width: Optional[int] = None,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: Optional[str] = None,
    allow_abbrev: Optional[bool] = None,
    exit_on_error: Optional[bool] = None,
) -> Union[type[T], Callable[[type[T]], type[T]]]

Configure a class to parse command-line arguments.

Parameters:

  • cls (Optional[type[T]], default: None ) –

    The class to be decorated (when used without parentheses).

  • name (str, default: basename(argv[0]) ) –

    Overrides the runtime-determined name of the program.

  • version (Optional[str], default: None ) –

    Sets the version for the short version (-V) and help messages.

  • long_version (Optional[str], default: None ) –

    Sets the version for the long version (--version) and help messages.

  • usage (Optional[str], default: None ) –

    The string describing the program usage. The default is generated from arguments added to parser.

  • about (Optional[str], default: None ) –

    The program's description for the short help (-h).

  • long_about (Optional[str], default: None ) –

    The program's description for the long help (--help).

  • after_help (Optional[str], default: None ) –

    Free-form help text for after auto-generated short help (-h).

  • after_long_help (Optional[str], default: None ) –

    Free-form help text for after auto-generated long help (--help).

  • before_help (Optional[str], default: None ) –

    Free-form help text for before auto-generated short help (-h).

  • before_long_help (Optional[str], default: None ) –

    Free-form help text for before auto-generated long help (--help).

  • subcommand_help_heading (str, default: 'Commands' ) –

    The help heading used for subcommands when printing help.

  • subcommand_value_name (str, default: 'COMMAND' ) –

    The value name used for subcommands when printing usage and help.

  • color (Optional[ColorChoice], default: None ) –

    When to color output.

  • styles (Optional[Styles], default: None ) –

    The styles for help output.

  • help_template (Optional[str], default: None ) –

    The help template to be used, overriding the default format.

  • max_term_width (Optional[int], default: None ) –

    The help output will wrap to min(max_term_width, shutil.get_terminal_size()).

  • propagate_version (bool, default: False ) –

    Whether to use the version of the current command for all subcommands.

  • disable_version_flag (bool, default: False ) –

    Disable the -V and --version flags.

  • disable_help_flag (bool, default: False ) –

    Disable the -h and --help flags.

  • prefix_chars (str, default: '-' ) –

    The set of characters that prefix optional arguments.

  • fromfile_prefix_chars (Optional[str], default: None ) –

    The set of characters that prefix files from which additional arguments should be read.

  • conflict_handler (Optional[str], default: None ) –

    The strategy for resolving conflicting optionals.

  • allow_abbrev (Optional[bool], default: None ) –

    Whether to allow long options to be abbreviated if the abbreviation is unambiguous.

  • exit_on_error (Optional[bool], default: None ) –

    Whether ArgumentParser exits with error info when an error occurs.

Example:

import clap

@clap.command(name="git", version="2.49.0")
class Cli(clap.Parser):
    """git - the stupid content tracker.

    Git is a fast, scalable, distributed revision control system with an
    unusually rich command set that provides both high-level operations and
    full access to internals.
    """
    ...
Source code in clap/api.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def command[T](
    cls: Optional[type[T]] = None,
    /,
    *,
    name: str = os.path.basename(sys.argv[0]),
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    usage: Optional[str] = None,
    about: Optional[str] = None,
    long_about: Optional[str] = None,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = None,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = None,
    subcommand_help_heading: str = "Commands",
    subcommand_value_name: str = "COMMAND",
    color: Optional[ColorChoice] = None,
    styles: Optional[Styles] = None,
    help_template: Optional[str] = None,
    max_term_width: Optional[int] = None,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: Optional[str] = None,
    allow_abbrev: Optional[bool] = None,
    exit_on_error: Optional[bool] = None,
) -> Union[type[T], Callable[[type[T]], type[T]]]:
    """Configure a class to parse command-line arguments.

    Args:
        cls: The class to be decorated (when used without parentheses).
        name: Overrides the runtime-determined name of the program.
        version: Sets the version for the short version (`-V`) and help messages.
        long_version: Sets the version for the long version (`--version`) and help messages.
        usage: The string describing the program usage. The default is
            generated from arguments added to parser.
        about: The program's description for the short help (`-h`).
        long_about: The program's description for the long help (`--help`).
        after_help: Free-form help text for after auto-generated short help (`-h`).
        after_long_help: Free-form help text for after auto-generated long help (`--help`).
        before_help: Free-form help text for before auto-generated short help (`-h`).
        before_long_help: Free-form help text for before auto-generated long help (`--help`).
        subcommand_help_heading: The help heading used for subcommands when printing help.
        subcommand_value_name: The value name used for subcommands when printing usage and help.
        color: When to color output.
        styles: The styles for help output.
        help_template: The help template to be used, overriding the default format.
        max_term_width: The help output will wrap to `min(max_term_width, shutil.get_terminal_size())`.
        propagate_version: Whether to use the version of the current command for all subcommands.
        disable_version_flag: Disable the `-V` and `--version` flags.
        disable_help_flag: Disable the `-h` and `--help` flags.
        prefix_chars: The set of characters that prefix optional arguments.
        fromfile_prefix_chars: The set of characters that prefix files from
            which additional arguments should be read.
        conflict_handler: The strategy for resolving conflicting optionals.
        allow_abbrev: Whether to allow long options to be abbreviated if the
            abbreviation is unambiguous.
        exit_on_error: Whether `ArgumentParser` exits with error info when an error occurs.

    Example:

    ```python
    import clap

    @clap.command(name="git", version="2.49.0")
    class Cli(clap.Parser):
        \"""git - the stupid content tracker.

        Git is a fast, scalable, distributed revision control system with an
        unusually rich command set that provides both high-level operations and
        full access to internals.
        \"""
        ...
    ```
    """
    def wrap(cls: type[T]) -> type[T]:
        nonlocal about, long_about, name
        if cls.__doc__ is not None:
            doc_about, doc_long_about = get_help_from_docstring(cls.__doc__.strip())
            if about is None:
                about = doc_about
            if long_about is None:
                long_about = doc_long_about
        command = Command(
            name=name,
            usage=usage,
            version=version,
            long_version=long_version,
            about=about,
            long_about=long_about,
            before_help=before_help,
            before_long_help=before_long_help,
            after_help=after_help,
            after_long_help=after_long_help,
            subcommand_help_heading=subcommand_help_heading,
            subcommand_value_name=subcommand_value_name,
            color=color,
            styles=styles,
            help_template=help_template,
            max_term_width=max_term_width,
            propagate_version=propagate_version,
            disable_version_flag=disable_version_flag,
            disable_help_flag=disable_help_flag,
            prefix_chars=prefix_chars,
            fromfile_prefix_chars=fromfile_prefix_chars,
            conflict_handler=conflict_handler,
            allow_abbrev=allow_abbrev,
            exit_on_error=exit_on_error,
        )
        setattr(cls, _COMMAND_DATA, command)
        setattr(cls, _PARSER, create_parser(cls))

        # delete default values of fields so that `@dataclass` does not complain
        # about mutable defaults (`Arg`)
        for name, _ in cls.__annotations__.items():
            if hasattr(cls, name):
                delattr(cls, name)

        @classmethod
        def parse_args(cls: type[T], args: Optional[list[str]] = None) -> T:
            """Parse command-line arguments and return an instance of the class."""
            parser = getattr(cls, _PARSER)
            parsed_args = parser.parse_args(args)
            obj = object.__new__(cls)
            apply_parsed_args(dict(parsed_args._get_kwargs()), obj)
            return obj

        cls.parse_args = parse_args
        return cls

    if cls is None:
        return wrap
    return wrap(cls)