Skip to content

Latest commit

 

History

History
84 lines (53 loc) · 1.48 KB

File metadata and controls

84 lines (53 loc) · 1.48 KB

PYTHON Python::jsonargparse

CLI usage

jsonargparse is a library for creating command-line interfaces (CLIs) and making Python apps easily configurable. I prefer this to the famous argparse module, because it has more advanced features (loading config files, auto create, …​) while keeping simple usage.

Using CLI

Creates "greetings.py" with :

greetings.py
from jsonargparse import CLI


def greetings(name: str):  # your main parameters and logic here
    print(f'Hello, {name}.')


def main():
    # Automatically add all arguments from greetings parameters
    CLI(greetings)


if __name__ == '__main__':
    main()

Use it as follows:

$>sh
$> python ./greetings.py Friend
Hello, Friend.

Add short aliases

Creates "greetings.py" with :

greetings.py
from jsonargparse import CLI, ArgumentParser


def greetings(name: str = ''):  # you must define a default value here
    print(f'Il mio nome è {name}.')


class AliasingParser(ArgumentParser):
    def add_argument(self, *args, **kwargs):
        if args == ('--name',): ags += ('-n',)
        return super().add_argument(*args, **kwargs)


def main():
    CLI(greetings, parser_class=AliasingParser)


if __name__ == '__main__':
    main()

Use it as follows:

$>sh
$> python ./greetings.py -n Nessuno
Il mio nome è Nessuno.