config-argument-parser


Nameconfig-argument-parser JSON
Version 1.5.0 PyPI version JSON
download
home_pagehttps://github.com/yuanx749/config-argument-parser
SummaryA package to help automatically create command-line interface from configuration or code.
upload_time2024-11-21 09:41:46
maintainerNone
docs_urlNone
authorXiao Yuan
requires_python>=3.8
licenseMIT License
keywords cli option argument parameter flag configuration parser command comment dataclass python
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # config-argument-parser

[![PyPI version](https://badge.fury.io/py/config-argument-parser.svg)](https://badge.fury.io/py/config-argument-parser)
[![Downloads](https://static.pepy.tech/badge/config-argument-parser/month)](https://pepy.tech/project/config-argument-parser)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/b15383188a354af684ba9d49b09cc253)](https://app.codacy.com/gh/yuanx749/config-argument-parser/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
[![Maintainability](https://api.codeclimate.com/v1/badges/288bbabbf406afe66e37/maintainability)](https://codeclimate.com/github/yuanx749/config-argument-parser/maintainability)
[![codecov](https://codecov.io/gh/yuanx749/config-argument-parser/branch/dev/graph/badge.svg?token=W34MFRGVMY)](https://codecov.io/gh/yuanx749/config-argument-parser)
[![Documentation Status](https://readthedocs.org/projects/config-argument-parser/badge/?version=latest)](https://config-argument-parser.readthedocs.io/en/latest/?badge=latest)

A package to help automatically create command-line interface from configuration or code.

It contains three modules CAP🧢(`ConfigArgumentParser`), TAP🚰(`TypeArgumentParser`), and GAP🕳️(`GlobalArgumentParser`).

Read the documentation [here](http://config-argument-parser.readthedocs.io/).

## Motivation

Configuration files are highly readable and useful for specifying options, but sometimes they are not convenient as command-line interface. However, it requires writing a lot of code to produce a CLI. This package automates the building process, by utilizing the Python standard libraries `configparser` and `argparse`.

The design is to minimize the changes to your original scripts, so as to facilitate maintenance.

## Features

- Only few extra lines are needed to build a CLI from an existing script.
- The comments are parsed as help messages. (Most libraries do not preserve the comments.)
- Consistent format between configuration and script provides ease of use.

## Usage

### Case 1: create CLI from an object

If you use class to store arguments, such as the script `example.py` below.

```Python
import configargparser

class Args:
    # Help message of the first argument. Help is optional.
    a_string = "abc"
    a_float = 1.23  # inline comments are omitted
    # Help can span multiple lines.
    # This is another line.
    a_boolean = False
    an_integer = 0

args = Args()

parser = configargparser.ConfigArgumentParser()
parser.parse_obj(args, shorts="sfb")

print(args.a_string)
print(args.a_float)
print(args.a_boolean)
print(args.an_integer)
```

In fact, only the snippet below is added to the original script. Moreover, removing this minimal modification does not affect the original script. `shorts` is optional. If provided, add short options for the first few arguments in order.

```Python
import configargparser
parser = configargparser.ConfigArgumentParser()
parser.parse_obj(args)
```

Default arguments are defined as class attributes, and parsed arguments are stored as instance attributes. The good is that auto-completion can be triggered in editors.

Show help, `python example.py -h`:

```console
$ python example.py -h
usage: example.py [-h] [-s A_STRING] [-f A_FLOAT] [-b] [--an-integer AN_INTEGER]

options:
  -h, --help            show this help message and exit
  -s A_STRING, --a-string A_STRING
                        Help message of the first argument. Help is optional. (default: abc)
  -f A_FLOAT, --a-float A_FLOAT
                        a_float (default: 1.23)
  -b, --a-boolean       Help can span multiple lines. This is another line. (default: False)
  --an-integer AN_INTEGER
                        an_integer (default: 0)
```

Run with options, for example, `python example.py -b -f 1`:

```console
$ python example.py -b -f 1
abc
1.0
True
0
```

Note that the values are changed.

For the best practice, see [Case 4](#case-4-create-cli-from-a-dataclass-object-preferred).

### Case 2: create CLI from configuration

If you use configuration file, create an example script `example.py`:

```Python
import configargparser

parser = configargparser.ConfigArgumentParser()
parser.read("config.ini")
parser.parse_args(shorts="sfb")

print("Configs:", parser.defaults)
print("Args:   ", parser.args)
```

Create a configuration file `config.ini` in the same directory:

```ini
[DEFAULT]
# Help message of the first argument. Help is optional.
a_string = 'abc'
a_float = 1.23  # inline comments are omitted
# Help can span multiple lines.
# This is another line.
a_boolean = False
an_integer = 0
```

Regular run, `python example.py`:

```console
$ python example.py
Configs: {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}
Args:    {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}
```

Run with options, such as `python example.py -b -f 1`:

```console
$ python example.py -b -f 1
Configs: {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}
Args:    {'a_string': 'abc', 'a_float': 1.0, 'a_boolean': True, 'an_integer': 0}
```

### Case 3: create CLI from global variables

If you use global variables, define the variables at top of file as the script `example.py` below:

```Python
# [DEFAULT]
# Help message of the first argument. Help is optional.
a_string = "abc"
a_float = 1.23  # inline comments are omitted
# Help can span multiple lines.
# This is another line.
a_boolean = False
an_integer = 0
# [END]

import configargparser

parser = configargparser.ConfigArgumentParser()
parser.read_py("example.py")
parser.parse_args(shorts="sfb")

# update global variables
globals().update(parser.args)
print(a_string)
print(a_float)
print(a_boolean)
print(an_integer)
```

Use it as in case 1. For example, `python example.py -b -f 1`:

```console
$ python example.py -b -f 1
abc
1.0
True
0
```

### Case 4: create CLI from a dataclass object (preferred)

Suppose you have a script `example.py` below, which uses a `dataclass` object to store arguments:

```Python
from dataclasses import dataclass

@dataclass
class Args:
    # Help message of the first argument. Help is optional.
    a_string: str = "abc"
    a_float: float = 1.23  # inline comments are omitted
    # Help can span multiple lines.
    # This is another line.
    a_boolean: bool = False
    an_integer: int = 0

args = Args()
```

Add these lines to the script to create CLI:

```Python
import configargparser
parser = configargparser.TypeArgumentParser()
parser.parse_obj(args, shorts="sfb")

print(args)
```

Use it as in case 1. For example, `python example.py -b -f 1` to change the values:

```console
$ python example.py -b -f 1
Args(a_string='abc', a_float=1.0, a_boolean=True, an_integer=0)
```

### Case 5: create CLI from global variables (without comments)

This requires less code than case 3, but the comments are not parsed, as the script `example.py` below:

```Python
a_string = "abc"
a_float = 1.23
a_boolean = False
an_integer = 0

import configargparser

parser = configargparser.GlobalArgumentParser()
parser.parse_globals(shorts="sfb")

print(a_string)
print(a_float)
print(a_boolean)
print(an_integer)
```

Use it as in case 1. For example, `python example.py -b -f 1`:

```console
$ python example.py -b -f 1
abc
1.0
True
0
```

## Installation

Install from PyPI:

```bash
python -m pip install --upgrade pip
pip install config-argument-parser
```

Alternatively, install from source:

```bash
git clone https://github.com/yuanx749/config-argument-parser.git
cd config-argument-parser
```

then install in development mode:

```bash
git checkout main
python -m pip install --upgrade pip
pip install -e .
```

or:

```bash
git checkout dev
python -m pip install --upgrade pip
pip install -e .[dev]
pre-commit install
```

Uninstall:

```bash
pip uninstall config-argument-parser
```

## Notes

This package uses [Semantic Versioning](https://semver.org/).

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/yuanx749/config-argument-parser",
    "name": "config-argument-parser",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "CLI, option, argument, parameter, flag, configuration, parser, command, comment, dataclass, Python",
    "author": "Xiao Yuan",
    "author_email": "yuanx749@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ed/61/cd2fdc7a24eecb99a15ff0ef725428ee94e9b73ab9c6bde48f4a6e6096a0/config_argument_parser-1.5.0.tar.gz",
    "platform": null,
    "description": "# config-argument-parser\r\n\r\n[![PyPI version](https://badge.fury.io/py/config-argument-parser.svg)](https://badge.fury.io/py/config-argument-parser)\r\n[![Downloads](https://static.pepy.tech/badge/config-argument-parser/month)](https://pepy.tech/project/config-argument-parser)\r\n[![Codacy Badge](https://app.codacy.com/project/badge/Grade/b15383188a354af684ba9d49b09cc253)](https://app.codacy.com/gh/yuanx749/config-argument-parser/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)\r\n[![Maintainability](https://api.codeclimate.com/v1/badges/288bbabbf406afe66e37/maintainability)](https://codeclimate.com/github/yuanx749/config-argument-parser/maintainability)\r\n[![codecov](https://codecov.io/gh/yuanx749/config-argument-parser/branch/dev/graph/badge.svg?token=W34MFRGVMY)](https://codecov.io/gh/yuanx749/config-argument-parser)\r\n[![Documentation Status](https://readthedocs.org/projects/config-argument-parser/badge/?version=latest)](https://config-argument-parser.readthedocs.io/en/latest/?badge=latest)\r\n\r\nA package to help automatically create command-line interface from configuration or code.\r\n\r\nIt contains three modules CAP\ud83e\udde2(`ConfigArgumentParser`), TAP\ud83d\udeb0(`TypeArgumentParser`), and GAP\ud83d\udd73\ufe0f(`GlobalArgumentParser`).\r\n\r\nRead the documentation [here](http://config-argument-parser.readthedocs.io/).\r\n\r\n## Motivation\r\n\r\nConfiguration files are highly readable and useful for specifying options, but sometimes they are not convenient as command-line interface. However, it requires writing a lot of code to produce a CLI. This package automates the building process, by utilizing the Python standard libraries `configparser` and `argparse`.\r\n\r\nThe design is to minimize the changes to your original scripts, so as to facilitate maintenance.\r\n\r\n## Features\r\n\r\n- Only few extra lines are needed to build a CLI from an existing script.\r\n- The comments are parsed as help messages. (Most libraries do not preserve the comments.)\r\n- Consistent format between configuration and script provides ease of use.\r\n\r\n## Usage\r\n\r\n### Case 1: create CLI from an object\r\n\r\nIf you use class to store arguments, such as the script `example.py` below.\r\n\r\n```Python\r\nimport configargparser\r\n\r\nclass Args:\r\n    # Help message of the first argument. Help is optional.\r\n    a_string = \"abc\"\r\n    a_float = 1.23  # inline comments are omitted\r\n    # Help can span multiple lines.\r\n    # This is another line.\r\n    a_boolean = False\r\n    an_integer = 0\r\n\r\nargs = Args()\r\n\r\nparser = configargparser.ConfigArgumentParser()\r\nparser.parse_obj(args, shorts=\"sfb\")\r\n\r\nprint(args.a_string)\r\nprint(args.a_float)\r\nprint(args.a_boolean)\r\nprint(args.an_integer)\r\n```\r\n\r\nIn fact, only the snippet below is added to the original script. Moreover, removing this minimal modification does not affect the original script. `shorts` is optional. If provided, add short options for the first few arguments in order.\r\n\r\n```Python\r\nimport configargparser\r\nparser = configargparser.ConfigArgumentParser()\r\nparser.parse_obj(args)\r\n```\r\n\r\nDefault arguments are defined as class attributes, and parsed arguments are stored as instance attributes. The good is that auto-completion can be triggered in editors.\r\n\r\nShow help, `python example.py -h`:\r\n\r\n```console\r\n$ python example.py -h\r\nusage: example.py [-h] [-s A_STRING] [-f A_FLOAT] [-b] [--an-integer AN_INTEGER]\r\n\r\noptions:\r\n  -h, --help            show this help message and exit\r\n  -s A_STRING, --a-string A_STRING\r\n                        Help message of the first argument. Help is optional. (default: abc)\r\n  -f A_FLOAT, --a-float A_FLOAT\r\n                        a_float (default: 1.23)\r\n  -b, --a-boolean       Help can span multiple lines. This is another line. (default: False)\r\n  --an-integer AN_INTEGER\r\n                        an_integer (default: 0)\r\n```\r\n\r\nRun with options, for example, `python example.py -b -f 1`:\r\n\r\n```console\r\n$ python example.py -b -f 1\r\nabc\r\n1.0\r\nTrue\r\n0\r\n```\r\n\r\nNote that the values are changed.\r\n\r\nFor the best practice, see [Case 4](#case-4-create-cli-from-a-dataclass-object-preferred).\r\n\r\n### Case 2: create CLI from configuration\r\n\r\nIf you use configuration file, create an example script `example.py`:\r\n\r\n```Python\r\nimport configargparser\r\n\r\nparser = configargparser.ConfigArgumentParser()\r\nparser.read(\"config.ini\")\r\nparser.parse_args(shorts=\"sfb\")\r\n\r\nprint(\"Configs:\", parser.defaults)\r\nprint(\"Args:   \", parser.args)\r\n```\r\n\r\nCreate a configuration file `config.ini` in the same directory:\r\n\r\n```ini\r\n[DEFAULT]\r\n# Help message of the first argument. Help is optional.\r\na_string = 'abc'\r\na_float = 1.23  # inline comments are omitted\r\n# Help can span multiple lines.\r\n# This is another line.\r\na_boolean = False\r\nan_integer = 0\r\n```\r\n\r\nRegular run, `python example.py`:\r\n\r\n```console\r\n$ python example.py\r\nConfigs: {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}\r\nArgs:    {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}\r\n```\r\n\r\nRun with options, such as `python example.py -b -f 1`:\r\n\r\n```console\r\n$ python example.py -b -f 1\r\nConfigs: {'a_string': 'abc', 'a_float': 1.23, 'a_boolean': False, 'an_integer': 0}\r\nArgs:    {'a_string': 'abc', 'a_float': 1.0, 'a_boolean': True, 'an_integer': 0}\r\n```\r\n\r\n### Case 3: create CLI from global variables\r\n\r\nIf you use global variables, define the variables at top of file as the script `example.py` below:\r\n\r\n```Python\r\n# [DEFAULT]\r\n# Help message of the first argument. Help is optional.\r\na_string = \"abc\"\r\na_float = 1.23  # inline comments are omitted\r\n# Help can span multiple lines.\r\n# This is another line.\r\na_boolean = False\r\nan_integer = 0\r\n# [END]\r\n\r\nimport configargparser\r\n\r\nparser = configargparser.ConfigArgumentParser()\r\nparser.read_py(\"example.py\")\r\nparser.parse_args(shorts=\"sfb\")\r\n\r\n# update global variables\r\nglobals().update(parser.args)\r\nprint(a_string)\r\nprint(a_float)\r\nprint(a_boolean)\r\nprint(an_integer)\r\n```\r\n\r\nUse it as in case 1. For example, `python example.py -b -f 1`:\r\n\r\n```console\r\n$ python example.py -b -f 1\r\nabc\r\n1.0\r\nTrue\r\n0\r\n```\r\n\r\n### Case 4: create CLI from a dataclass object (preferred)\r\n\r\nSuppose you have a script `example.py` below, which uses a `dataclass` object to store arguments:\r\n\r\n```Python\r\nfrom dataclasses import dataclass\r\n\r\n@dataclass\r\nclass Args:\r\n    # Help message of the first argument. Help is optional.\r\n    a_string: str = \"abc\"\r\n    a_float: float = 1.23  # inline comments are omitted\r\n    # Help can span multiple lines.\r\n    # This is another line.\r\n    a_boolean: bool = False\r\n    an_integer: int = 0\r\n\r\nargs = Args()\r\n```\r\n\r\nAdd these lines to the script to create CLI:\r\n\r\n```Python\r\nimport configargparser\r\nparser = configargparser.TypeArgumentParser()\r\nparser.parse_obj(args, shorts=\"sfb\")\r\n\r\nprint(args)\r\n```\r\n\r\nUse it as in case 1. For example, `python example.py -b -f 1` to change the values:\r\n\r\n```console\r\n$ python example.py -b -f 1\r\nArgs(a_string='abc', a_float=1.0, a_boolean=True, an_integer=0)\r\n```\r\n\r\n### Case 5: create CLI from global variables (without comments)\r\n\r\nThis requires less code than case 3, but the comments are not parsed, as the script `example.py` below:\r\n\r\n```Python\r\na_string = \"abc\"\r\na_float = 1.23\r\na_boolean = False\r\nan_integer = 0\r\n\r\nimport configargparser\r\n\r\nparser = configargparser.GlobalArgumentParser()\r\nparser.parse_globals(shorts=\"sfb\")\r\n\r\nprint(a_string)\r\nprint(a_float)\r\nprint(a_boolean)\r\nprint(an_integer)\r\n```\r\n\r\nUse it as in case 1. For example, `python example.py -b -f 1`:\r\n\r\n```console\r\n$ python example.py -b -f 1\r\nabc\r\n1.0\r\nTrue\r\n0\r\n```\r\n\r\n## Installation\r\n\r\nInstall from PyPI:\r\n\r\n```bash\r\npython -m pip install --upgrade pip\r\npip install config-argument-parser\r\n```\r\n\r\nAlternatively, install from source:\r\n\r\n```bash\r\ngit clone https://github.com/yuanx749/config-argument-parser.git\r\ncd config-argument-parser\r\n```\r\n\r\nthen install in development mode:\r\n\r\n```bash\r\ngit checkout main\r\npython -m pip install --upgrade pip\r\npip install -e .\r\n```\r\n\r\nor:\r\n\r\n```bash\r\ngit checkout dev\r\npython -m pip install --upgrade pip\r\npip install -e .[dev]\r\npre-commit install\r\n```\r\n\r\nUninstall:\r\n\r\n```bash\r\npip uninstall config-argument-parser\r\n```\r\n\r\n## Notes\r\n\r\nThis package uses [Semantic Versioning](https://semver.org/).\r\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "A package to help automatically create command-line interface from configuration or code.",
    "version": "1.5.0",
    "project_urls": {
        "Documentation": "http://config-argument-parser.readthedocs.io/",
        "Homepage": "https://github.com/yuanx749/config-argument-parser",
        "Source": "https://github.com/yuanx749/config-argument-parser"
    },
    "split_keywords": [
        "cli",
        " option",
        " argument",
        " parameter",
        " flag",
        " configuration",
        " parser",
        " command",
        " comment",
        " dataclass",
        " python"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "83c9751ebae9e3c3fa46f18016505f8892058a59796d927a5e0757c79faefd7c",
                "md5": "631c693f2ac1905b3ecea44156bf1a30",
                "sha256": "53df2580193e076c812db19792e6b96b32abd2aa67dde82c93ba2a54195e5c4f"
            },
            "downloads": -1,
            "filename": "config_argument_parser-1.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "631c693f2ac1905b3ecea44156bf1a30",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 9228,
            "upload_time": "2024-11-21T09:41:45",
            "upload_time_iso_8601": "2024-11-21T09:41:45.018444Z",
            "url": "https://files.pythonhosted.org/packages/83/c9/751ebae9e3c3fa46f18016505f8892058a59796d927a5e0757c79faefd7c/config_argument_parser-1.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ed61cd2fdc7a24eecb99a15ff0ef725428ee94e9b73ab9c6bde48f4a6e6096a0",
                "md5": "cf4735af3b2120478e2ebc776d2d1c61",
                "sha256": "7e6ae74879a1150908c87a477290de65533caf8605ecb39a05f819f3c5ea582c"
            },
            "downloads": -1,
            "filename": "config_argument_parser-1.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "cf4735af3b2120478e2ebc776d2d1c61",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 8217,
            "upload_time": "2024-11-21T09:41:46",
            "upload_time_iso_8601": "2024-11-21T09:41:46.197314Z",
            "url": "https://files.pythonhosted.org/packages/ed/61/cd2fdc7a24eecb99a15ff0ef725428ee94e9b73ab9c6bde48f4a6e6096a0/config_argument_parser-1.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-21 09:41:46",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yuanx749",
    "github_project": "config-argument-parser",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "config-argument-parser"
}
        
Elapsed time: 0.44466s