Argparse

Introduction

The Argparse Extension provides the ArgparseArgumentHandler for argument parsing, and the ArgparseController for runtime dispatch. Both are the defaults used by Cement.

Documentation References:

API References

Requirements

  • No external dependencies

Configuration

This extension does not rely on any application level configuration settings or meta options.

Usage

The following is an example application using both the ArgparseArgumentHandler and ArgparseController. Note that the default arg_handler is already set toArgparseArgumentHandler by App.

from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'
        arguments = [
            (['--base-foo'],
             {'help': 'base foo option'}),
        ]

    @ex(hide=True)
    def default(self):
        print('Inside Base.default')

        if self.app.pargs.base_foo:
            # do something with self.app.pargs.base_foo
            print('Base Foo > %s' % self.app.pargs.base_foo)

    @ex(
        arguments=[
            (['--command1-opt'],
             {'help': 'option under command1',
              'action': 'store_true'})
        ],
        aliases=['cmd1'],
        help='sub-command under myapp base controller',
    )
    def command1(self):
        print('Inside Base.command1')

        if self.app.pargs.command1_opt:
            # do something with self.app.pargs.command1_opt
            pass

class Embedded(Controller):
    class Meta:
        label = 'embedded_controller'
        stacked_on = 'base'
        stacked_type = 'embedded'

    @expose(help="embedded under base controller")
    def command2(self):
        print('Inside Embedded.command2')

class Nested(Controller):
    class Meta:
        label = 'nested_controller'
        stacked_on = 'base'
        stacked_type = 'nested'
        arguments = [
            (['--nested-opt'],
             {'help': 'option under nested-controller'}),
        ]

    @expose(help="sub-command under nested-controller")
    def command3(self):
        print('Inside Nested.command3')

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
            Embedded,
            Nested,
        ]

with MyApp() as app:
    app.run()

Last updated