Cement 3

CLI application framework for Python.

Cement handles config, arguments, logging, output, plugins and caching, so you write the commands. Core has no dependencies and every piece can be replaced. It works for a single-file script and for a multi-tier application.

pip install cement
myapp.py
from cement import App, Controller, ex


class Base(Controller):
    class Meta:
        label = 'base'

    @ex(
        help='say hello',
        arguments=[
            (['-n', '--name'], {'default': 'world'}),
        ],
    )
    def hello(self):
        self.app.log.info(f'hello {self.app.pargs.name}')


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


with MyApp() as app:
    app.run()
$ python myapp.py hello --name cement
INFO: hello cement
0core dependencies
100%test coverage
typedmypy compliant
3.10+python
2009first commit
BSD-3license

Features

All of this is in core and works with no setup. Each piece is a handler behind an interface, so you can replace it with your own.

interfaces + handlers

Every core service is an interface with a default handler. Register your own handler to replace it.

controllers

Sub-commands and nested controllers, written as classes and decorated methods.

config

Defaults, config files and environment variables merge into one config object.

arguments

Command-line arguments are parsed with argparse and merged with config.

logging

Console and file logging, set up from config.

output + templates

Commands return a dict and an output handler renders it: JSON, YAML, a table or a template.

plugins

Load plugins at runtime so users can add commands to your app.

cache

A cache interface, with Redis and memcached handlers available as extensions.

hooks

Run your code at defined points in the app lifecycle, or define your own hooks.

Extensions

Extensions add handlers for other backends. The ones that need third-party packages declare them as extras, so core stays dependency-free.

  • alarm
  • argparse
  • colorlog
  • configparser
  • daemon
  • generate
  • jinja2
  • json
  • logging
  • memcached
  • mustache
  • plugin
  • print
  • redis
  • scrub
  • smtp
  • tabulate
  • watchdog
  • yaml

Install extras with pip install "cement[yaml,colorlog]"

myapp.py
class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['yaml', 'colorlog', 'jinja2']

        config_handler = 'yaml'
        log_handler = 'colorlog'
        output_handler = 'jinja2'

Quickstart

  1. install the developer tools

    $ pip install "cement[cli]"
  2. generate a project

    $ cement generate project ./myapp
  3. run it

    $ cd myapp && pip install -e .
    $ myapp --help

The 20-minute tutorial in the developer guide builds a todo app with a database backend and a CRUD controller.