Skip to content

Sub-commands

In a file named 2-sub-commands.py:

from arger import Arger
from tests.utils import _reprint

arger = Arger(prog="pytest", description="App Description goes here")

container = []


@arger.add_cmd
def create(name: str):
    """Create a new test.

    :param name: Name of the test
    """
    container.append(container)
    _reprint(**locals())


@arger.add_cmd
def remove(*name: str):
    """Remove a test with variadic arguments.

    :param name: Tests to remove
    """
    if name in container:
        container.remove(remove)
    _reprint(**locals())


@arger.add_cmd
def list():
    """List all tests."""
    _reprint(**locals(), container=container)


if __name__ == "__main__":
    arger.run()

Usage

  • Show main app help message

    $ python docs/examples/2-sub-commands.py -h
    usage: pytest [-h] {create,remove,list} ...
    
    App Description goes here
    
    options:
      -h, --help            show this help message and exit
    
    commands:
      {create,remove,list}
        create              Create a new test.
        remove              Remove a test with variadic arguments.
        list                List all tests.
    

  • Show help message for 'create' sub-command

    $ python docs/examples/2-sub-commands.py create -h
    usage: pytest create [-h] name
    
    Create a new test.
    
    positional arguments:
      name        Name of the test
    
    options:
      -h, --help  show this help message and exit
    

  • Show help message for 'remove' sub-command

    $ python docs/examples/2-sub-commands.py remove -h
    usage: pytest remove [-h] [name ...]
    
    Remove a test with variadic arguments.
    
    positional arguments:
      name        Tests to remove (default: None)
    
    options:
      -h, --help  show this help message and exit
    

  • Show help message for 'list' sub-command

    $ python docs/examples/2-sub-commands.py list -h
    usage: pytest list [-h]
    
    List all tests.
    
    options:
      -h, --help  show this help message and exit
    

  • Run 'create' sub-command with a positional argument

    $ python docs/examples/2-sub-commands.py create folder1
    name (<class 'str'>): folder1
    

  • Run 'remove' sub-command with multiple variadic arguments

    $ python docs/examples/2-sub-commands.py remove folder1 folder2
    name (<class 'tuple'>): ('folder1', 'folder2')
    

  • Run 'list' sub-command

    $ python docs/examples/2-sub-commands.py list
    container (<class 'list'>): []