ArgParseDecorator


NameArgParseDecorator JSON
Version 1.4.0 PyPI version JSON
download
home_pagehttps://github.com/innot/argparseDecorator
SummaryA tool to easily build command line interpreters
upload_time2024-10-13 10:42:07
maintainerNone
docs_urlNone
authorThomas Holland
requires_pythonNone
licenseMIT
keywords 'argparse argumentparser decorator tool cli commandline'
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![License](https://img.shields.io/github/license/innot/ArgParseDecorator)](https://github.com/innot/argparseDecorator/blob/master/LICENSE.txt)
![Python Version](https://img.shields.io/pypi/pyversions/ArgParseDecorator)
[![pypi](https://img.shields.io/pypi/v/ArgParseDecorator.svg)](https://pypi.org/project/ArgParseDecorator)
[![Documentation Status](https://readthedocs.org/projects/argparsedecorator/badge/?version=latest)](https://argparsedecorator.readthedocs.io/en/latest/?badge=latest)
[![Build](https://github.com/innot/argparseDecorator/actions/workflows/ci.yaml/badge.svg)](https://github.com/innot/argparseDecorator/actions/workflows/ci.yaml)
[![codecov](https://codecov.io/gh/innot/argparseDecorator/branch/master/graph/badge.svg?token=IPZB3RQUXD)](https://codecov.io/gh/innot/argparseDecorator)


# About

argparseDecorator is a tool to ease working with the [argparse](https://docs.python.org/3/library/argparse.html)
library to build custom command line interpreters.

Instead of setting up the [ArgumentParser](https://docs.python.org/3/library/argparse.html#argumentparser-objects)
object by hand and then adding subcommands and all the required arguments the argparseDecorator supplies a
custom [decorator](https://docs.python.org/3/glossary.html#term-decorator)
to mark any function as a command and to generate the ArgumentParser from the function signature.

With this it is quite easy to make command line interfaces like, for example, a shell like cli:

```python
from argparsedecorator import *

cli = ArgParseDecorator()


@cli.command
def ls(arg1, arg2, arg3):
    ...


@cli.command
def mv(...):
    ...


@cli.command
def cp(...):
    ...

cmdline = input()
cli.execute(cmdline)
```

The ArgParseDecorator uses both the signature of the decorated function and its
[docstring](https://peps.python.org/pep-0257/) to infer information, metadata and description of the function arguments
and passes them to the underlying ArgumentParser.

Here is an example for using ArgParseDecorator to create a hypothetical 'ls' command:

```python

from __future__ import annotations  # required for Python 3.8 and 3.9. Not required for Python 3.10+
from argparsedecorator import *  # import the ArgParseDecorator API

cli = ArgParseDecorator()


@cli.command
def ls(
        files: ZeroOrMore[str],
        a: Flag = False,  # create '-a' flag that is 'False' if '-a' is not in the command line.
        ignore: Option | Exactly1[str] = "",  # create optional '--ignore PATTERN' argument
        columns: Option | int | Choices[Literal["range(1,5)"]] = 1,  # valid input for '--columns' is 1 to 4
        sort: Option | Choices[Literal["fwd", "rev"]] = "fwd",  # '--sort {fwd,rev}' with default 'fwd'
):
    """
    List information about files (the current directory by default).
    :param files: List of files, may be empty.

    :param a: do not ignore entries strating with '.'
    :alias a: --all

    :param ignore: do not list entries matching PATTERN
    :metavar ignore: PATTERN

    :param columns: number of output columns, must be between 1 and 4. Default is 1
    :alias columns: -c

    :param sort: alphabetic direction of output, either 'fwd' (default) or 'rev'
    :alias sort: -s
    """
    # for demonstration just return all input back to the caller, i.e. parser.execute(...)
    return {"files": files, "a": a, "ignore": ignore, "columns": columns, "sort": sort}
```

This example shows how annotations are used to add some metadata to the arguments which will be used by the argparse
library to interpret the command line input. Take a look at the
[documentation](https://argparsedecorator.readthedocs.io/en/latest/usage.html#function-signature)
to learn more about the supported annotations.

Now a command line can be parsed and executed like this:

```python
result = cli.execute("ls -a -c 2 --sort rev --ignore *.log")
```

ArgParseDecorator uses the docstring of the decorated function to get a help string for the command, and it also parses
[Sphinx](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html) style directives to provide help strings
for arguments as well as additional metadata that can not be written as annotations.

The information provided by the docstring is used by the built-in help command:

```python
parser.execute("help ls")
```

```
usage:  ls [-a] [--ignore PATTERN] [--columns {1,2,3,4}] [--sort {fwd,rev}] [files ...]

List information about files (the current directory by default).

positional arguments:
  files                 List of files, may be empty.

options:
  -a, --all             do not ignore entries strating with '.'
  --ignore PATTERN      do not list entries matching PATTERN
  --columns {1,2,3,4}, -c {1,2,3,4}
                        number of output columns, must be between 1 and 4
  --sort {fwd,rev}, -s {fwd,rev}
                        alphabetic direction of output, either 'fwd' (default) or 'rev'
```

## Requirements

* Works best with Python 3.10 or higher
    - the new type unions with '|' make the annotations much more readable

* Works with Python 3.8+
    - some features require the use of 'from \_\_future\_\_ import annotations'

* No other dependencies

## Installation

If the requirements are met, then a simple

```bash
 $ pip import argparseDecorator
```

will install the argParseDecorator module.

## Documentation

Comprehensive documentation is available at https://argparseDecorator.readthedocs.io/.

## Version
* 1.4.0
  * added ``ignore_annotations`` and ``ignore_docstring`` flags
* 1.3.1
  * Fixed some bugs in the documentation
* 1.3.0
  * Added support for command aliases
  * New Annotations: ``RequiredFlag``, ``RequiredOption``
* 1.2.0 
  * Added support for sys.argv argument lists in execute()
  * Using shlex to split commandlines into tokens
  * Numerous minor bug fixes
* 1.1.0 
  * Added support for execute_async()
* 1.0.2 
  * Added support for quoted input to the execute method 
* 1.0.1 
  * first release

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/innot/argparseDecorator",
    "name": "ArgParseDecorator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "'argparse ArgumentParser decorator tool cli commandline'",
    "author": "Thomas Holland",
    "author_email": "thomas@innot.de",
    "download_url": "https://files.pythonhosted.org/packages/f7/ed/ea6fe16145e9c8779ea94f16b502f110c56f8b53306f4b87a9fed9874925/argparsedecorator-1.4.0.tar.gz",
    "platform": null,
    "description": "[![License](https://img.shields.io/github/license/innot/ArgParseDecorator)](https://github.com/innot/argparseDecorator/blob/master/LICENSE.txt)\n![Python Version](https://img.shields.io/pypi/pyversions/ArgParseDecorator)\n[![pypi](https://img.shields.io/pypi/v/ArgParseDecorator.svg)](https://pypi.org/project/ArgParseDecorator)\n[![Documentation Status](https://readthedocs.org/projects/argparsedecorator/badge/?version=latest)](https://argparsedecorator.readthedocs.io/en/latest/?badge=latest)\n[![Build](https://github.com/innot/argparseDecorator/actions/workflows/ci.yaml/badge.svg)](https://github.com/innot/argparseDecorator/actions/workflows/ci.yaml)\n[![codecov](https://codecov.io/gh/innot/argparseDecorator/branch/master/graph/badge.svg?token=IPZB3RQUXD)](https://codecov.io/gh/innot/argparseDecorator)\n\n\n# About\n\nargparseDecorator is a tool to ease working with the [argparse](https://docs.python.org/3/library/argparse.html)\nlibrary to build custom command line interpreters.\n\nInstead of setting up the [ArgumentParser](https://docs.python.org/3/library/argparse.html#argumentparser-objects)\nobject by hand and then adding subcommands and all the required arguments the argparseDecorator supplies a\ncustom [decorator](https://docs.python.org/3/glossary.html#term-decorator)\nto mark any function as a command and to generate the ArgumentParser from the function signature.\n\nWith this it is quite easy to make command line interfaces like, for example, a shell like cli:\n\n```python\nfrom argparsedecorator import *\n\ncli = ArgParseDecorator()\n\n\n@cli.command\ndef ls(arg1, arg2, arg3):\n    ...\n\n\n@cli.command\ndef mv(...):\n    ...\n\n\n@cli.command\ndef cp(...):\n    ...\n\ncmdline = input()\ncli.execute(cmdline)\n```\n\nThe ArgParseDecorator uses both the signature of the decorated function and its\n[docstring](https://peps.python.org/pep-0257/) to infer information, metadata and description of the function arguments\nand passes them to the underlying ArgumentParser.\n\nHere is an example for using ArgParseDecorator to create a hypothetical 'ls' command:\n\n```python\n\nfrom __future__ import annotations  # required for Python 3.8 and 3.9. Not required for Python 3.10+\nfrom argparsedecorator import *  # import the ArgParseDecorator API\n\ncli = ArgParseDecorator()\n\n\n@cli.command\ndef ls(\n        files: ZeroOrMore[str],\n        a: Flag = False,  # create '-a' flag that is 'False' if '-a' is not in the command line.\n        ignore: Option | Exactly1[str] = \"\",  # create optional '--ignore PATTERN' argument\n        columns: Option | int | Choices[Literal[\"range(1,5)\"]] = 1,  # valid input for '--columns' is 1 to 4\n        sort: Option | Choices[Literal[\"fwd\", \"rev\"]] = \"fwd\",  # '--sort {fwd,rev}' with default 'fwd'\n):\n    \"\"\"\n    List information about files (the current directory by default).\n    :param files: List of files, may be empty.\n\n    :param a: do not ignore entries strating with '.'\n    :alias a: --all\n\n    :param ignore: do not list entries matching PATTERN\n    :metavar ignore: PATTERN\n\n    :param columns: number of output columns, must be between 1 and 4. Default is 1\n    :alias columns: -c\n\n    :param sort: alphabetic direction of output, either 'fwd' (default) or 'rev'\n    :alias sort: -s\n    \"\"\"\n    # for demonstration just return all input back to the caller, i.e. parser.execute(...)\n    return {\"files\": files, \"a\": a, \"ignore\": ignore, \"columns\": columns, \"sort\": sort}\n```\n\nThis example shows how annotations are used to add some metadata to the arguments which will be used by the argparse\nlibrary to interpret the command line input. Take a look at the\n[documentation](https://argparsedecorator.readthedocs.io/en/latest/usage.html#function-signature)\nto learn more about the supported annotations.\n\nNow a command line can be parsed and executed like this:\n\n```python\nresult = cli.execute(\"ls -a -c 2 --sort rev --ignore *.log\")\n```\n\nArgParseDecorator uses the docstring of the decorated function to get a help string for the command, and it also parses\n[Sphinx](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html) style directives to provide help strings\nfor arguments as well as additional metadata that can not be written as annotations.\n\nThe information provided by the docstring is used by the built-in help command:\n\n```python\nparser.execute(\"help ls\")\n```\n\n```\nusage:  ls [-a] [--ignore PATTERN] [--columns {1,2,3,4}] [--sort {fwd,rev}] [files ...]\n\nList information about files (the current directory by default).\n\npositional arguments:\n  files                 List of files, may be empty.\n\noptions:\n  -a, --all             do not ignore entries strating with '.'\n  --ignore PATTERN      do not list entries matching PATTERN\n  --columns {1,2,3,4}, -c {1,2,3,4}\n                        number of output columns, must be between 1 and 4\n  --sort {fwd,rev}, -s {fwd,rev}\n                        alphabetic direction of output, either 'fwd' (default) or 'rev'\n```\n\n## Requirements\n\n* Works best with Python 3.10 or higher\n    - the new type unions with '|' make the annotations much more readable\n\n* Works with Python 3.8+\n    - some features require the use of 'from \\_\\_future\\_\\_ import annotations'\n\n* No other dependencies\n\n## Installation\n\nIf the requirements are met, then a simple\n\n```bash\n $ pip import argparseDecorator\n```\n\nwill install the argParseDecorator module.\n\n## Documentation\n\nComprehensive documentation is available at https://argparseDecorator.readthedocs.io/.\n\n## Version\n* 1.4.0\n  * added ``ignore_annotations`` and ``ignore_docstring`` flags\n* 1.3.1\n  * Fixed some bugs in the documentation\n* 1.3.0\n  * Added support for command aliases\n  * New Annotations: ``RequiredFlag``, ``RequiredOption``\n* 1.2.0 \n  * Added support for sys.argv argument lists in execute()\n  * Using shlex to split commandlines into tokens\n  * Numerous minor bug fixes\n* 1.1.0 \n  * Added support for execute_async()\n* 1.0.2 \n  * Added support for quoted input to the execute method \n* 1.0.1 \n  * first release\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A tool to easily build command line interpreters",
    "version": "1.4.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/innot/argparseDecorator/issues",
        "Documentation": "https://argparsedecorator.readthedocs.io/en/latest/",
        "Homepage": "https://github.com/innot/argparseDecorator"
    },
    "split_keywords": [
        "'argparse",
        "argumentparser",
        "decorator",
        "tool",
        "cli",
        "commandline'"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5fd6cb9553ac3ab1411c454b9acd3d4a03daa0e5cae684d75c4f97d8f2a92628",
                "md5": "8d3cd35e59b3af21fefdabccf6692152",
                "sha256": "b88b3b7ed095b64a32d3daefaa1cde09813a7c6fe0d7f6a5f67a449b551c68f8"
            },
            "downloads": -1,
            "filename": "ArgParseDecorator-1.4.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8d3cd35e59b3af21fefdabccf6692152",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 27696,
            "upload_time": "2024-10-13T10:42:06",
            "upload_time_iso_8601": "2024-10-13T10:42:06.065228Z",
            "url": "https://files.pythonhosted.org/packages/5f/d6/cb9553ac3ab1411c454b9acd3d4a03daa0e5cae684d75c4f97d8f2a92628/ArgParseDecorator-1.4.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f7edea6fe16145e9c8779ea94f16b502f110c56f8b53306f4b87a9fed9874925",
                "md5": "a68149710ee0b147e55c82a183bd4e02",
                "sha256": "c3a9500fce4515e989963d1163170ba173e49aab6728d8260079d960d368e1d3"
            },
            "downloads": -1,
            "filename": "argparsedecorator-1.4.0.tar.gz",
            "has_sig": false,
            "md5_digest": "a68149710ee0b147e55c82a183bd4e02",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 34817,
            "upload_time": "2024-10-13T10:42:07",
            "upload_time_iso_8601": "2024-10-13T10:42:07.783449Z",
            "url": "https://files.pythonhosted.org/packages/f7/ed/ea6fe16145e9c8779ea94f16b502f110c56f8b53306f4b87a9fed9874925/argparsedecorator-1.4.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-13 10:42:07",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "innot",
    "github_project": "argparseDecorator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "argparsedecorator"
}
        
Elapsed time: 0.32906s