main.py
The main application is defined in main.py
:
1import sys
2
3from cliff.app import App
4from cliff.commandmanager import CommandManager
5
6
7class DemoApp(App):
8
9 def __init__(self):
10 super(DemoApp, self).__init__(
11 description='cliff demo app',
12 version='0.1',
13 command_manager=CommandManager('cliff.demo'),
14 deferred_help=True,
15 )
16
17 def initialize_app(self, argv):
18 self.LOG.debug('initialize_app')
19
20 def prepare_to_run_command(self, cmd):
21 self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
22
23 def clean_up(self, cmd, result, err):
24 self.LOG.debug('clean_up %s', cmd.__class__.__name__)
25 if err:
26 self.LOG.debug('got an error: %s', err)
27
28
29def main(argv=sys.argv[1:]):
30 myapp = DemoApp()
31 return myapp.run(argv)
32
33
34if __name__ == '__main__':
35 sys.exit(main(sys.argv[1:]))
The DemoApp
class inherits from App
and overrides
__init__()
to set the program description and version number. It also
passes a CommandManager
instance configured to look for plugins in the
cliff.demo
namespace.
The initialize_app()
method of DemoApp
will be invoked after the
main program arguments are parsed, but before any command processing is
performed and before the application enters interactive mode. This hook is
intended for opening connections to remote web services, databases, etc. using
arguments passed to the main application.
The prepare_to_run_command()
method of DemoApp
will be invoked
after a command is identified, but before the command is given its arguments
and run. This hook is intended for pre-command validation or setup that must be
repeated and cannot be handled by initialize_app()
.
The clean_up()
method of DemoApp
is invoked after a command
runs. If the command raised an exception, the exception object is passed to
clean_up()
. Otherwise the err
argument is None
.
The main()
function defined in main.py
is registered as a console
script entry point so that DemoApp
can be run from the command line
(see the discussion of setup.py
below).
simple.py
Two commands are defined in simple.py
:
1import logging
2
3from cliff.command import Command
4
5
6class Simple(Command):
7 "A simple command that prints a message."
8
9 log = logging.getLogger(__name__)
10
11 def take_action(self, parsed_args):
12 self.log.info('sending greeting')
13 self.log.debug('debugging')
14 self.app.stdout.write('hi!\n')
15
16
17class Error(Command):
18 "Always raises an error"
19
20 log = logging.getLogger(__name__)
21
22 def take_action(self, parsed_args):
23 self.log.info('causing error')
24 raise RuntimeError('this is the expected exception')
Simple
demonstrates using logging to emit messages on the console at
different verbose levels:
(.venv)$ cliffdemo simple
sending greeting
hi!
(.venv)$ cliffdemo -v simple
prepare_to_run_command Simple
sending greeting
debugging
hi!
clean_up Simple
(.venv)$ cliffdemo -q simple
hi!
Error
always raises a RuntimeError
exception when it is
invoked, and can be used to experiment with the error handling features of
cliff:
(.venv)$ cliffdemo error
causing error
ERROR: this is the expected exception
(.venv)$ cliffdemo -v error
prepare_to_run_command Error
causing error
ERROR: this is the expected exception
clean_up Error
got an error: this is the expected exception
(.venv)$ cliffdemo --debug error
causing error
this is the expected exception
Traceback (most recent call last):
File ".../cliff/app.py", line 218, in run_subcommand
result = cmd.run(parsed_args)
File ".../cliff/command.py", line 43, in run
self.take_action(parsed_args)
File ".../demoapp/cliffdemo/simple.py", line 24, in take_action
raise RuntimeError('this is the expected exception')
RuntimeError: this is the expected exception
Traceback (most recent call last):
File "/Users/dhellmann/Envs/cliff/bin/cliffdemo", line 9, in <module>
load_entry_point('cliffdemo==0.1', 'console_scripts', 'cliffdemo')()
File ".../demoapp/cliffdemo/main.py", line 33, in main
return myapp.run(argv)
File ".../cliff/app.py", line 160, in run
result = self.run_subcommand(remainder)
File ".../cliff/app.py", line 218, in run_subcommand
result = cmd.run(parsed_args)
File ".../cliff/command.py", line 43, in run
self.take_action(parsed_args)
File ".../demoapp/cliffdemo/simple.py", line 24, in take_action
raise RuntimeError('this is the expected exception')
RuntimeError: this is the expected exception
list.py
list.py
includes a single command derived from cliff.lister.Lister
which prints a list of the files in the current directory.
1import logging
2import os
3
4from cliff.lister import Lister
5
6
7class Files(Lister):
8 """Show a list of files in the current directory.
9
10 The file name and size are printed by default.
11 """
12
13 log = logging.getLogger(__name__)
14
15 def take_action(self, parsed_args):
16 return (('Name', 'Size'),
17 ((n, os.stat(n).st_size) for n in os.listdir('.'))
18 )
Files
prepares the data, and Lister
manages the output
formatter and printing the data to the console:
(.venv)$ cliffdemo files
+---------------+------+
| Name | Size |
+---------------+------+
| build | 136 |
| cliffdemo.log | 2546 |
| Makefile | 5569 |
| source | 408 |
+---------------+------+
(.venv)$ cliffdemo files -f csv
"Name","Size"
"build",136
"cliffdemo.log",2690
"Makefile",5569
"source",408
show.py
show.py
includes a single command derived from cliff.show.ShowOne
which prints the properties of the named file.
1import logging
2import os
3
4from cliff.show import ShowOne
5
6
7class File(ShowOne):
8 "Show details about a file"
9
10 log = logging.getLogger(__name__)
11
12 def get_parser(self, prog_name):
13 parser = super(File, self).get_parser(prog_name)
14 parser.add_argument('filename', nargs='?', default='.')
15 return parser
16
17 def take_action(self, parsed_args):
18 stat_data = os.stat(parsed_args.filename)
19 columns = ('Name',
20 'Size',
21 'UID',
22 'GID',
23 'Modified Time',
24 )
25 data = (parsed_args.filename,
26 stat_data.st_size,
27 stat_data.st_uid,
28 stat_data.st_gid,
29 stat_data.st_mtime,
30 )
31 return (columns, data)
File
prepares the data, and ShowOne
manages the output
formatter and printing the data to the console:
(.venv)$ cliffdemo file setup.py
+---------------+--------------+
| Field | Value |
+---------------+--------------+
| Name | setup.py |
| Size | 5825 |
| UID | 502 |
| GID | 20 |
| Modified Time | 1335569964.0 |
+---------------+--------------+
setup.py
The demo application is packaged using setuptools.
1#!/usr/bin/env python
2
3from setuptools import find_packages
4from setuptools import setup
5
6PROJECT = 'cliffdemo'
7
8# Change docs/sphinx/conf.py too!
9VERSION = '0.1'
10
11try:
12 long_description = open('README.rst', 'rt').read()
13except IOError:
14 long_description = ''
15
16setup(
17 name=PROJECT,
18 version=VERSION,
19
20 description='Demo app for cliff',
21 long_description=long_description,
22
23 author='Doug Hellmann',
24 author_email='doug.hellmann@gmail.com',
25
26 url='https://github.com/openstack/cliff',
27 download_url='https://github.com/openstack/cliff/tarball/master',
28
29 classifiers=[
30 'Development Status :: 3 - Alpha',
31 'License :: OSI Approved :: Apache Software License',
32 'Programming Language :: Python',
33 'Programming Language :: Python :: 3',
34 'Programming Language :: Python :: 3 :: Only',
35 'Intended Audience :: Developers',
36 'Environment :: Console',
37 ],
38
39 platforms=['Any'],
40
41 scripts=[],
42
43 provides=[],
44 install_requires=['cliff'],
45
46 namespace_packages=[],
47 packages=find_packages(),
48 include_package_data=True,
49
50 entry_points={
51 'console_scripts': [
52 'cliffdemo = cliffdemo.main:main'
53 ],
54 'cliff.demo': [
55 'simple = cliffdemo.simple:Simple',
56 'two_part = cliffdemo.simple:Simple',
57 'error = cliffdemo.simple:Error',
58 'list files = cliffdemo.list:Files',
59 'files = cliffdemo.list:Files',
60 'file = cliffdemo.show:File',
61 'show file = cliffdemo.show:File',
62 'unicode = cliffdemo.encoding:Encoding',
63 'hooked = cliffdemo.hook:Hooked',
64 ],
65 'cliff.demo.hooked': [
66 'sample-hook = cliffdemo.hook:Hook',
67 ],
68 },
69
70 zip_safe=False,
71)
The important parts of the packaging instructions are the entry_points
settings. All of the commands are registered in the cliff.demo
namespace.
Each main program should define its own command namespace so that it only loads
the command plugins that it should be managing.