Cement Application Framework for Python
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
- breaking Cement 3.x officially dropped support for Python 2.x. It requires Python >=3.8. Applications developed with older Cement versions targeting Python 2.x will require significant migration efforts.
- breaking As of Cement 3.0.12, dependencies for the `cement` command-line development tool (specifically `PyYAML` and `Jinja2`) were moved to an optional `cement[cli]` extra. Existing automation or scripts that rely on the `cement` command without this extra installed will break.
- gotcha Native Windows development support for Cement is not 100% complete and is not a primary development target. Users developing on Windows are recommended to use Docker for a more streamlined experience, as native setups may encounter known issues.
Install
-
pip install cement -
pip install cement[cli]
Imports
- App
from cement import App
- Controller
from cement import Controller
- ex
from cement import ex
- CementApp
Quickstart
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)