aghast
aghast

Reputation: 15310

Does Click support "bunching" short options together?

Certain command line tools allow "bunching" of short options.

For example, the tar command takes short options -x, -v, and -f filespec. It allows the options to be bunched together like -xvf filespec to avoid the redundant typing of space-dash.

Reading the documentation for Click I cannot find any indication if this is supported or not.

The documentation does say that alternative prefix characters (like +w/-w) are supported, which tends to suggest that perhaps it is not supported.

So:

  1. Does click support bunching together short options?

  2. If so, is this automatic, or does it need to be configured?

  3. What is the search keyword I should use to find documentation for this?

Upvotes: 3

Views: 233

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

Click definitely supports stacking short flag options. Not sure that is it necessarily documented in the click docs, but this is a standard POSIX command line convention as documented here. The second bullet point of why to use Click states:

  • supports implementation of Unix/POSIX command line conventions

Test code:

import click

@click.command()
@click.option('-x', is_flag=True)
@click.option('-y', is_flag=True)
@click.option('-z')
def cli(x, y, z):
    click.echo(f'x:{x}  y:{y}  z:{z}')


if __name__ == "__main__":
    commands = (
        '-x',
        '-y',
        '-z 1',
        '-xz 2',
        '-yz 3',
        '-xyz 4',
        '-yx',
        '--help',
    )

    import sys, time
    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

Results:

Click Version: 7.1.2
Python Version: 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
-----------
> -x
x:True  y:False  z:None
-----------
> -y
x:False  y:True  z:None
-----------
> -z 1
x:False  y:False  z:1
-----------
> -xz 2
x:True  y:False  z:2
-----------
> -yz 3
x:False  y:True  z:3
-----------
> -xyz 4
x:True  y:True  z:4
-----------
> -yx
x:True  y:True  z:None
-----------
> --help
Usage: test_code.py [OPTIONS]

Options:
  -x
  -y
  -z TEXT
  --help   Show this message and exit.

Upvotes: 2

Related Questions