helptext 1.1.22
A documentation-generated argument parser.
Requires Python: >=3
Keywords: helptext, help, text, option, argument, parser, cli

# helptext - a documentation-generated argument parser

```py
"""
Usage: demo.py [OPTIONS] [OPERANDS...]

A brief demonstration of the helptext module.

OPTIONS
  --defaults               default option values
  -a, --alpha FOO          flag aliases and captured arguments
  -b bar, --bravo=baz      alternate argument syntax
"""

import sys
from helptext import parse

opts, operands = parse(__doc__, sys.argv[1:])
```

```py
$ python3 -i ./examples/demo.py -a b c
>>> opts['--defaults']
{'enabled': False, 'count': 0, 'argument': False, 'value': None}
>>> opts['-a'] is opts['--alpha']
True
>>> opts['--alpha']
{'enabled': True, 'count': 1, 'argument': True, 'value': 'b'}
>>> operands
['c']
```

## Installation

```
pip install helptext
```

## API

This module provides a single function.

```py
helptext.parse(doc, args, posixly_correct=False)
```

Parses command-line arguments as defined by a program's help text.

> **NOTE:**
> This interface is intended to be stable, well-behaved, and minimal.
>
> For a more featureful alternative, see the [`magic`](#magic) submodule.

_doc_ is a string containing an option list, preferably `__doc__` as described
in [PEP 257 – Docstring Conventions][1]. _args_ is a string or list of strings
representing command-line arguments, typically `sys.argv[1:]`.

Returns a dictionary _opts_ and a list of string _operands_. _opts_ describes
the options defined in _doc_ and contains the arguments belonging to those
options, while the remaining non-option arguments become _operands_.

If _posixly_correct_ is `True`, operand intermixing is disabled. As with the
explicit `--` end of options delimiter, non-option arguments also terminate
parsing, preserving strict positional order and option-like operands.

Raises `ValueError` on command-line argument parsing errors.

## Options

_opts_ is a dictionary of options, keyed by their flags.

```py
{
    '--defaults': {
        'enabled': False,
        'count': 0,
        'argument': False,
        'value': None,
    },
}
```

Any line in _doc_ beginning with a valid flag becomes an option. A POSIX-style
flag is a dash followed by a single alphanumeric character (e.g. `-a`, `-B`).
GNU-style flags are prefixed with two dashes and typically consist of one to
three alphanumeric words separated by dashes (e.g. `--alpha`,
`--bravo-charlie-delta`).

Leading whitespace is ignored and line processing is terminated by the next two
consecutive spaces to avoid inline option descriptions. All flags on a line are
aliases to the same option. Any non-flag words configure the option to require
an argument. Commas are optional and ignored. Long flags may also be depicted
with arguments attached by an equals sign (e.g. `--example=ARG`).

Each option is a dictionary containing:

 - A boolean _enabled_, `True` when the option has been invoked in _args_.
 - An integer _count_ of the option's total number of invocations in _args_.
 - A boolean _argument_, `True` when an option-argument is required.
 - A string _value_, representing the option-argument, default `None`.

## Magic

This submodule provides a function and two exceptions.

```py
helptext.magic.parse(doc=None, args=None, posixly_correct=None, **kwargs):
```

This function is a drop-in replacement for `helptext.parse()`, with additional
convenience features.

### Enhancements

```py
"""
Usage: magic.py [OPTIONS]

A dazzling showcase of the helptext.magic submodule.

OPTIONS
  -h, --help               display this help text and exit
  --version                display version information and exit
"""

from helptext.magic import parse

__version__ = '1.0.0'

opts, operands = parse()
```

1. If _doc_ is `None`, it defaults to `__main__.__doc__`.

2. If _args_ is `None`, it defaults to `sys.argv[1:]`.

3. If _posixly_correct_ is `None`, the `POSIXLY_CORRECT` environment variable
is used. `False` when unset, `True` if set to any value (including empty).

```py
$ python3 ./examples/demo.py -x
Traceback (most recent call last):
  File "[...]/examples/demo.py", line 15, in <module>
    opts, operands = parse(__doc__, sys.argv[1:])
                     ~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "[...]/site-packages/helptext/__init__.py", line 43, in parse
    raise ValueError("invalid option -- '%s'" % s[1])
ValueError: invalid option -- 'x'
```

```
$ python3 ./examples/magic.py -x
./examples/magic.py: invalid option -- 'x'
Try 'magic.py --help' for more information.
```

4. Command-line errors raise `HelptextError` instead of `ValueError`, printing
a message to `stderr` and initiating a system exit with code `1`.

5. Accepts _prog_ as a keyword argument. This string represents the command
name special parameter `$0`. _prog_ is prepended to `HelptextError` messages
(e.g. `prog: invalid option -- 'x'`). Default is `sys.argv[0]`. If `--help` is
defined in _doc_, add a hint to the message as well. Set to `''` to disable
enhanced error messages.

```
$ python3 ./examples/magic.py -h
Usage: magic.py [OPTIONS] [OPERANDS...]

A brief demonstration of the helptext.magic submodule.

OPTIONS
  -h, --help               display this help text and exit
  --version                display version information and exit
```

6. If `--help` is defined as an option in _doc_ and any of its flag aliases
are invoked in _args_, `HelptextHelper` is raised, printing _doc_ to `stdout`
and initiating a system exit with code `0`.

```
$ python3 ./examples/magic.py --version
1.0.0
```

7. Accepts _version_ as a keyword argument. Similar to `--help`, if
`--version` is defined as an option in _doc_ and any of its flag aliases are
invoked in _args_, `HelptextHelper` is raised, printing _version_ to `stdout`
and initiating a system exit with code `0`. Default is `__main__.__version__`,
if defined. Set to `''` to disable this behavior.

## Exceptions

```py
exception helptext.magic.HelptextError
```

Raised when a command-line argument parsing error occurs. It is a subclass of
`SystemExit`.


```py
exception helptext.magic.HelptextHelper
```

Raised by `--help` or `--version` to display program information. It is a
subclass of `SystemExit`.

## Unsupported Behavior

### Short Long Options
`Usage: prog -alpha`

This is a deprecated format reserved for legacy utilities.  New code is
expected to use POSIX-style short options and/or GNU-style long options.

### Required Options

`Usage: prog -a ARG`

Set sensible defaults or use a positional parameter, instead.

### Mutually-exclusive Options

`Usage: prog [-a | -b]`

Divide distinct modes of operation into separate utilities or have the user
select a value from a list with an option-argument or positional parameter.

### Optional Option-arguments

`Usage: prog [-a [ARG]]`

Split the option into one that takes an argument and one that does not.

### Multiple Option-arguments

`Usage: prog [-a ARG...]`

Use comma- or space-separated values within a single option-argument (e.g.
`a,b,c` or `"a b c"`). Inner values can also accept arguments, attached with an
equals sign (e.g. `a=1,b=2,c=3`).

[1]: https://peps.python.org/pep-0257