Skip to main content

Cleo allows you to create beautiful and testable command-line interfaces.

Project description

Cleo

Poetry Tests PyPI version

Create beautiful and testable command-line interfaces.

Resources

Usage

To make a command that greets you from the command line, create greet_command.py and add the following to it:

from cleo.commands.command import Command
from cleo.helpers import argument, option

class GreetCommand(Command):
    name = "greet"
    description = "Greets someone"
    arguments = [
        argument(
            "name",
            description="Who do you want to greet?",
            optional=True
        )
    ]
    options = [
        option(
            "yell",
            "y",
            description="If set, the task will yell in uppercase letters",
            flag=True
        )
    ]

    def handle(self):
        name = self.argument("name")

        if name:
            text = f"Hello {name}"
        else:
            text = "Hello"

        if self.option("yell"):
            text = text.upper()

        self.line(text)

You also need to create the file application.py to run at the command line which creates an Application and adds commands to it:

#!/usr/bin/env python

from greet_command import GreetCommand

from cleo.application import Application


application = Application()
application.add(GreetCommand())

if __name__ == "__main__":
    application.run()

Test the new command by running the following

$ python application.py greet John

This will print the following to the command line:

Hello John

You can also use the --yell option to make everything uppercase:

$ python application.py greet John --yell

This prints:

HELLO JOHN

Coloring the Output

Whenever you output text, you can surround the text with tags to color its output. For example:

# blue text
self.line("<info>foo</info>")

# green text
self.line("<comment>foo</comment>")

# cyan text
self.line("<question>foo</question>")

# bold red text
self.line("<error>foo</error>")

The closing tag can be replaced by </>, which revokes all formatting options established by the last opened tag.

It is possible to define your own styles using the add_style() method:

self.add_style("fire", fg="red", bg="yellow", options=["bold", "blink"])
self.line("<fire>foo</fire>")

Available foreground and background colors are: black, red, green, yellow, blue, magenta, cyan and white.

And available options are: bold, underscore, blink, reverse and conceal.

You can also set these colors and options inside the tag name:

# green text
self.line("<fg=green>foo</>")

# black text on a cyan background
self.line("<fg=black;bg=cyan>foo</>")

# bold text on a yellow background
self.line("<bg=yellow;options=bold>foo</>")

Verbosity Levels

Cleo has four verbosity levels. These are defined in the Output class:

Mode Meaning Console option
Verbosity.QUIET Do not output any messages -q or --quiet
Verbosity.NORMAL The default verbosity level (none)
Verbosity.VERBOSE Increased verbosity of messages -v
Verbosity.VERY_VERBOSE Informative non essential messages -vv
Verbosity.DEBUG Debug messages -vvv

It is possible to print a message in a command for only a specific verbosity level. For example:

if Verbosity.VERBOSE <= self.io.verbosity:
    self.line(...)

There are also more semantic methods you can use to test for each of the verbosity levels:

if self.output.is_quiet():
    # ...

if self.output.is_verbose():
    # ...

You can also pass the verbosity flag directly to line().

self.line("", verbosity=Verbosity.VERBOSE)

When the quiet level is used, all output is suppressed.

Using Arguments

The most interesting part of the commands are the arguments and options that you can make available. Arguments are the strings - separated by spaces - that come after the command name itself. They are ordered, and can be optional or required. For example, add an optional last_name argument to the command and make the name argument required:

class GreetCommand(Command):
    name = "greet"
    description = "Greets someone"
    arguments = [
        argument(
            "name",
            description="Who do you want to greet?",
        ),
        argument(
            "last_name",
            description="Your last name?",
            optional=True
        )
    ]
    options = [
        option(
            "yell",
            "y",
            description="If set, the task will yell in uppercase letters",
            flag=True
        )
    ]

You now have access to a last_name argument in your command:

last_name = self.argument("last_name")
if last_name:
    text += f" {last_name}"

The command can now be used in either of the following ways:

$ python application.py greet John
$ python application.py greet John Doe

It is also possible to let an argument take a list of values (imagine you want to greet all your friends). For this it must be specified at the end of the argument list:

class GreetCommand(Command):
    name = "greet"
    description = "Greets someone"
    arguments = [
        argument(
            "names",
            description="Who do you want to greet?",
            multiple=True
        )
    ]
    options = [
        option(
            "yell",
            "y",
            description="If set, the task will yell in uppercase letters",
            flag=True
        )
    ]

To use this, just specify as many names as you want:

$ python application.py greet John Jane

You can access the names argument as a list:

names = self.argument("names")
if names:
    text = "Hello " + ", ".join(names)

Using Options

Unlike arguments, options are not ordered (meaning you can specify them in any order) and are specified with two dashes (e.g. --yell - you can also declare a one-letter shortcut that you can call with a single dash like -y). Options are always optional, and can be setup to accept a value (e.g. --dir=src) or simply as a boolean flag without a value (e.g. --yell).

Tip: It is also possible to make an option optionally accept a value (so that --yell or --yell=loud work). Options can also be configured to accept a list of values.

For example, add a new option to the command that can be used to specify how many times in a row the message should be printed:

class GreetCommand(Command):
    name = "greet"
    description = "Greets someone"
    arguments = [
        argument(
            "name",
            description="Who do you want to greet?",
            optional=True
        )
    ]
    options = [
        option(
            "yell",
            "y",
            description="If set, the task will yell in uppercase letters",
            flag=True
        ),
        option(
            "iterations",
            description="How many times should the message be printed?",
            default=1
        )
    ]

Next, use this in the command to print the message multiple times:

for _ in range(int(self.option("iterations"))):
    self.line(text)

Now, when you run the task, you can optionally specify a --iterations flag:

$ python application.py greet John
$ python application.py greet John --iterations=5

The first example will only print once, since iterations is empty and defaults to 1. The second example will print five times.

Recall that options don't care about their order. So, either of the following will work:

$ python application.py greet John --iterations=5 --yell
$ python application.py greet John --yell --iterations=5

Testing Commands

Cleo provides several tools to help you test your commands. The most useful one is the CommandTester class. It uses a special IO class to ease testing without a real console:

from greet_command import GreetCommand

from cleo.application import Application
from cleo.testers.command_tester import CommandTester


def test_execute():
    application = Application()
    application.add(GreetCommand())

    command = application.find("greet")
    command_tester = CommandTester(command)
    command_tester.execute()

    assert "..." == command_tester.io.fetch_output()

The CommandTester.io.fetch_output() method returns what would have been displayed during a normal call from the console. CommandTester.io.fetch_error() is also available to get what you have been written to the stderr.

You can test sending arguments and options to the command by passing them as a string to the CommandTester.execute() method:

from greet_command import GreetCommand

from cleo.application import Application
from cleo.testers.command_tester import CommandTester


def test_execute():
    application = Application()
    application.add(GreetCommand())

    command = application.find("greet")
    command_tester = CommandTester(command)
    command_tester.execute("John")

    assert "John" in command_tester.io.fetch_output()

You can also test a whole console application by using the ApplicationTester class.

Calling an existing Command

If a command depends on another one being run before it, instead of asking the user to remember the order of execution, you can call it directly yourself. This is also useful if you want to create a "meta" command that just runs a bunch of other commands.

Calling a command from another one is straightforward:

def handle(self):
    return_code = self.call("greet", "John --yell")
    return return_code

If you want to suppress the output of the executed command, you can use the call_silent() method instead.

Autocompletion

Cleo supports automatic (tab) completion in bash, zsh and fish.

By default, your application will have a completions command. To register these completions for your application, run one of the following in a terminal (replacing [program] with the command you use to run your application):

# Bash
[program] completions bash | sudo tee /etc/bash_completion.d/[program].bash-completion

# Bash - macOS/Homebrew (requires `brew install bash-completion`)
[program] completions bash > $(brew --prefix)/etc/bash_completion.d/[program].bash-completion

# Zsh
mkdir ~/.zfunc
echo "fpath+=~/.zfunc" >> ~/.zshrc
[program] completions zsh > ~/.zfunc/_[program]

# Zsh - macOS/Homebrew
[program] completions zsh > $(brew --prefix)/share/zsh/site-functions/_[program]

# Fish
[program] completions fish > ~/.config/fish/completions/[program].fish

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cleo-2.1.0.tar.gz (80.0 kB view details)

Uploaded Source

Built Distribution

cleo-2.1.0-py3-none-any.whl (78.7 kB view details)

Uploaded Python 3

File details

Details for the file cleo-2.1.0.tar.gz.

File metadata

  • Download URL: cleo-2.1.0.tar.gz
  • Upload date:
  • Size: 80.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.10.12 Linux/6.2.0-1015-azure

File hashes

Hashes for cleo-2.1.0.tar.gz
Algorithm Hash digest
SHA256 0b2c880b5d13660a7ea651001fb4acb527696c01f15c9ee650f377aa543fd523
MD5 30100b89b71435f2eade1b4a19191fb6
BLAKE2b-256 3c30f7960ed7041b158301c46774f87620352d50a9028d111b4211187af13783

See more details on using hashes here.

File details

Details for the file cleo-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: cleo-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 78.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.10.12 Linux/6.2.0-1015-azure

File hashes

Hashes for cleo-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4a31bd4dd45695a64ee3c4758f583f134267c2bc518d8ae9a29cf237d009b07e
MD5 d08afd1437716686f042c88bdc5dc443
BLAKE2b-256 2df56bbead8b880620e5a99e0e4bb9e22e67cca16ff48d54105302a3e7821096

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page