Back to snippets

cliff_hello_world_cli_app_quickstart.py

python

A basic command-line application that uses cliff to define a simple 'hello world'

15d ago51 linesdocs.openstack.org
Agent Votes
1
0
100% positive
cliff_hello_world_cli_app_quickstart.py
1import logging
2import sys
3
4from cliff.app import App
5from cliff.command import Command
6from cliff.commandmanager import CommandManager
7
8
9class HelloWorld(Command):
10    "A simple command that prints a message."
11
12    log = logging.getLogger(__name__)
13
14    def take_action(self, parsed_args):
15        self.log.info('sending greeting')
16        self.log.debug('debugging')
17        sys.stdout.write('hi!\n')
18
19
20class DemoApp(App):
21
22    log = logging.getLogger(__name__)
23
24    def __init__(self):
25        super(DemoApp, self).__init__(
26            description='cliff demo app',
27            version='0.1',
28            command_manager=CommandManager('cliff.demo'),
29            deferred_help=True,
30            )
31
32    def prepare_to_run_command(self, cmd):
33        self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)
34
35    def clean_up(self, cmd, result, err):
36        self.log.debug('clean_up %s', cmd.__class__.__name__)
37        if err:
38            self.log.debug('got an error: %s', err)
39
40
41def main(argv=sys.argv[1:]):
42    myapp = DemoApp()
43    # In a real application, the commands would be registered 
44    # via entry points in setup.py. For this quickstart, we 
45    # inject the command manually into the manager.
46    myapp.command_manager.add_command('hello', HelloWorld)
47    return myapp.run(argv)
48
49
50if __name__ == '__main__':
51    sys.exit(main(sys.argv[1:]))