config-argument-parser


Nameconfig-argument-parser JSON
Version 1.3.1 PyPI version JSON
download
home_pagehttps://github.com/yuanx749/config-argument-parser
SummaryA package help automatically create command-line interface from configuration or code.
upload_time2023-11-12 11:42:49
maintainer
docs_urlNone
authorXiao Yuan
requires_python>=3.7
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 help automatically create command-line interface from configuration or code.

It contains two modules CAP🧢(`ConfigArgumentParser`) and TAP🚰(`TypeArgumentParser`).

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 a 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 used class to store arguments, create a script `example.py` as below. 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.

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

```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()
# if `shorts` is provided, add short options for the first few arguments in order
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.

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

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]

optional arguments:
  -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
                        (default: 1.23)
  -b, --a-boolean       Help can span multiple lines. This is another line. (default: False)
  --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.

### Case 2: create CLI from configuration

If you used 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 script itself

If you used global variables, create a script `example.py`, with the variables defined at top of file as 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()

print(args.__dict__)
```

Add these lines to the script to create CLI:

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

print(args.__dict__)
```

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
{'a_string': 'abc', 'a_float': 1.0, 'a_boolean': True, 'an_integer': 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": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "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/ce/7b/d8fdf72c449a7e109db8870ac8bf9602da6fa0c7060e523cc34e6cde97cc/config-argument-parser-1.3.1.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 help automatically create command-line interface from configuration or code.\r\n\r\nIt contains two modules CAP\ud83e\udde2(`ConfigArgumentParser`) and TAP\ud83d\udeb0(`TypeArgumentParser`).\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 a 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 used class to store arguments, create a script `example.py` as below. 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.\r\n\r\nFor the best practice, see [Case 4](#case-4-create-cli-from-a-dataclass-object-preferred).\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\n# if `shorts` is provided, add short options for the first few arguments in order\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.\r\n\r\n```Python\r\nimport configargparser\r\nparser = configargparser.ConfigArgumentParser()\r\nparser.parse_obj(args)\r\n```\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\noptional arguments:\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                        (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                        (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\n### Case 2: create CLI from configuration\r\n\r\nIf you used 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 script itself\r\n\r\nIf you used global variables, create a script `example.py`, with the variables defined at top of file as 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\nprint(args.__dict__)\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.__dict__)\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\n{'a_string': 'abc', 'a_float': 1.0, 'a_boolean': True, 'an_integer': 0}\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 help automatically create command-line interface from configuration or code.",
    "version": "1.3.1",
    "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": "4075e436a321db662efe6664d34b245f87087ce5feaf68a7a8d7a076216d2815",
                "md5": "ab3149cbb5107298eca7dd1acc3b7985",
                "sha256": "090be126cb5daaab8e7b76ab73f4af3b1e63586a0e6c6bbbc3e75d35529a9eb9"
            },
            "downloads": -1,
            "filename": "config_argument_parser-1.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ab3149cbb5107298eca7dd1acc3b7985",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 8025,
            "upload_time": "2023-11-12T11:42:47",
            "upload_time_iso_8601": "2023-11-12T11:42:47.340603Z",
            "url": "https://files.pythonhosted.org/packages/40/75/e436a321db662efe6664d34b245f87087ce5feaf68a7a8d7a076216d2815/config_argument_parser-1.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ce7bd8fdf72c449a7e109db8870ac8bf9602da6fa0c7060e523cc34e6cde97cc",
                "md5": "7f73c00ec9aedca59ed2df35db0d1981",
                "sha256": "ad1e2cb3637d17bbd4bd7d8d87fbde2af2937d0305a6cfd866bfd305dc335a8a"
            },
            "downloads": -1,
            "filename": "config-argument-parser-1.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "7f73c00ec9aedca59ed2df35db0d1981",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 7747,
            "upload_time": "2023-11-12T11:42:49",
            "upload_time_iso_8601": "2023-11-12T11:42:49.105691Z",
            "url": "https://files.pythonhosted.org/packages/ce/7b/d8fdf72c449a7e109db8870ac8bf9602da6fa0c7060e523cc34e6cde97cc/config-argument-parser-1.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-12 11:42:49",
    "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.15283s