Cement Application Framework for Python

3.0.14 · active · verified Tue Apr 14

Cement is an advanced application framework for Python, primarily focused on Command Line Interfaces (CLI). It provides a versatile, stable, and feature-rich foundation for building simple to complex command-line and backend applications, offering the simplicity of a micro-framework with the capabilities of a mega-framework. The current version is 3.0.14, and it is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Cement application with a default command and a nested 'hello' sub-command. It showcases the `App` and `Controller` classes, along with the `ex` decorator for defining commands. Running `python myapp.py` will execute the default action, while `python myapp.py hello --help` or `python myapp.py hello name --name YourName` will demonstrate the sub-command.

import sys
from cement import App, Controller, ex

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

    @ex(hide=True)
    def _default(self):
        """Default action if no sub-command is passed."""
        print("Hello from Cement! Try 'myapp hello <name>'\n")
        print("Run with --help for options.")

class HelloWorld(Controller):
    class Meta:
        label = 'hello'
        stacked_on = 'base'
        stacked_type = 'nested'

    @ex(help="Say hello to a given name.")
    def name(self):
        """A sample sub-command."""
        name = self.app.pargs.name or "World"
        print(f"Hello, {name}!")

class MyApp(App):
    class Meta:
        label = 'myapp'
        base_controller = 'base'
        handlers = [
            Base,
            HelloWorld,
        ]

if __name__ == '__main__':
    try:
        with MyApp() as app:
            app.run()
    except Exception as e:
        print(f"An error occurred: {e}", file=sys.stderr)
        sys.exit(1)

view raw JSON →