Skip to main content

config-argument-parser

PyPI Codacy Badge codecov

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.

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.

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.

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:

$ 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:

$ 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 2: create CLI from configuration

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

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:

[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:

$ 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:

$ 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:

# [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:

$ 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:

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:

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:

$ 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:

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:

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

Installation

Install from PyPI:

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

Alternatively, install from source:

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

then install in development mode:

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

or:

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

Uninstall:

pip uninstall config-argument-parser

Notes

This package uses Semantic Versioning.

Metadata

Release files for config-argument-parser 1.5.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for config-argument-parser 1.5.3
File Size Uploaded Provenance
config_argument_parser-1.5.3.tar.gz 8.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for config-argument-parser 1.5.3
File Interpreter ABI Platform
config_argument_parser-1.5.3-py3-none-any.whl Python 3 none any Details

Total release size: 17.2 kB

Release files / config_argument_parser-1.5.3.tar.gz

Download URL config_argument_parser-1.5.3.tar.gz
Size 8.1 kB
Tags Source
SHA-256 checksum
How to use checksums
feb0720523edb016e83cd4d144bf91afc50bb35e757441aaf359c9f686985ae9
BLAKE2b-256 checksum
How to use checksums
65588a7b48c14a330550c002d0ee8db3c9835f6a1922088a17357e5e66377441
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Release files / config_argument_parser-1.5.3-py3-none-any.whl

Download URL config_argument_parser-1.5.3-py3-none-any.whl
Size 9.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c49fbee61d56cd8a45918c616710d136bd72990c1f646c663ba893c877fb45bb
BLAKE2b-256 checksum
How to use checksums
d20341a1031b0a9b105f4eb5ba33c1194378485c5d357cd0013fdffceb36de49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Security for config-argument-parser 1.5.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.5.3 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page