cleo


Namecleo JSON
Version 2.2.0 PyPI version JSON
download
home_pagehttps://github.com/python-poetry/cleo
SummaryCleo allows you to create beautiful and testable command-line interfaces.
upload_time2024-11-18 12:29:34
maintainerBranch Vincent
docs_urlNone
authorSébastien Eustace
requires_python<4.0,>=3.7
licenseMIT
keywords cli commands
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Cleo

[![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)](https://python-poetry.org/)
[![Tests](https://github.com/python-poetry/cleo/actions/workflows/tests.yml/badge.svg)](https://github.com/python-poetry/cleo/actions/workflows/tests.yml)
[![PyPI version](https://img.shields.io/pypi/v/cleo)](https://pypi.org/project/cleo/)

Create beautiful and testable command-line interfaces.

## Resources

- [Documentation](http://cleo.readthedocs.io)
- [Issue Tracker](https://github.com/python-poetry/cleo/issues)

## Usage

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

```python
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:

```python
#!/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

```bash
$ python application.py greet John
```

This will print the following to the command line:

```text
Hello John
```

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

```bash
$ python application.py greet John --yell
```

This prints:

```text
HELLO JOHN
```


### Coloring the Output

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

```python
# 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:

```python
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:

```python
# 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:

```python
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:

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

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

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

```python
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:

```python
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:

```python
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:

```bash
$ 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:

```python
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:

```bash
$ python application.py greet John Jane
```

You can access the `names` argument as a list:

```python
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:

```python
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:

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

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

```bash
$ 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:

```bash
$ 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:

```python
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:

```python
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:

```python
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
# 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
```


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/python-poetry/cleo",
    "name": "cleo",
    "maintainer": "Branch Vincent",
    "docs_url": null,
    "requires_python": "<4.0,>=3.7",
    "maintainer_email": "branchevincent@gmail.com",
    "keywords": "cli, commands",
    "author": "S\u00e9bastien Eustace",
    "author_email": "sebastien@eustace.io",
    "download_url": "https://files.pythonhosted.org/packages/8a/8a/2b50f680e45a17f5030395ba4e63ad20fa0ff74dee28a658239e74cd012c/cleo-2.2.0.tar.gz",
    "platform": null,
    "description": "# Cleo\n\n[![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)](https://python-poetry.org/)\n[![Tests](https://github.com/python-poetry/cleo/actions/workflows/tests.yml/badge.svg)](https://github.com/python-poetry/cleo/actions/workflows/tests.yml)\n[![PyPI version](https://img.shields.io/pypi/v/cleo)](https://pypi.org/project/cleo/)\n\nCreate beautiful and testable command-line interfaces.\n\n## Resources\n\n- [Documentation](http://cleo.readthedocs.io)\n- [Issue Tracker](https://github.com/python-poetry/cleo/issues)\n\n## Usage\n\nTo make a command that greets you from the command line, create\n`greet_command.py` and add the following to it:\n\n```python\nfrom cleo.commands.command import Command\nfrom cleo.helpers import argument, option\n\nclass GreetCommand(Command):\n    name = \"greet\"\n    description = \"Greets someone\"\n    arguments = [\n        argument(\n            \"name\",\n            description=\"Who do you want to greet?\",\n            optional=True\n        )\n    ]\n    options = [\n        option(\n            \"yell\",\n            \"y\",\n            description=\"If set, the task will yell in uppercase letters\",\n            flag=True\n        )\n    ]\n\n    def handle(self):\n        name = self.argument(\"name\")\n\n        if name:\n            text = f\"Hello {name}\"\n        else:\n            text = \"Hello\"\n\n        if self.option(\"yell\"):\n            text = text.upper()\n\n        self.line(text)\n```\n\nYou also need to create the file `application.py` to run at the command line which\ncreates an `Application` and adds commands to it:\n\n```python\n#!/usr/bin/env python\n\nfrom greet_command import GreetCommand\n\nfrom cleo.application import Application\n\n\napplication = Application()\napplication.add(GreetCommand())\n\nif __name__ == \"__main__\":\n    application.run()\n```\n\nTest the new command by running the following\n\n```bash\n$ python application.py greet John\n```\n\nThis will print the following to the command line:\n\n```text\nHello John\n```\n\nYou can also use the `--yell` option to make everything uppercase:\n\n```bash\n$ python application.py greet John --yell\n```\n\nThis prints:\n\n```text\nHELLO JOHN\n```\n\n\n### Coloring the Output\n\nWhenever you output text, you can surround the text with tags to color\nits output. For example:\n\n```python\n# blue text\nself.line(\"<info>foo</info>\")\n\n# green text\nself.line(\"<comment>foo</comment>\")\n\n# cyan text\nself.line(\"<question>foo</question>\")\n\n# bold red text\nself.line(\"<error>foo</error>\")\n```\n\nThe closing tag can be replaced by `</>`, which revokes all formatting\noptions established by the last opened tag.\n\nIt is possible to define your own styles using the `add_style()` method:\n\n```python\nself.add_style(\"fire\", fg=\"red\", bg=\"yellow\", options=[\"bold\", \"blink\"])\nself.line(\"<fire>foo</fire>\")\n```\n\nAvailable foreground and background colors are: `black`, `red`, `green`,\n`yellow`, `blue`, `magenta`, `cyan` and `white`.\n\nAnd available options are: `bold`, `underscore`, `blink`, `reverse` and\n`conceal`.\n\nYou can also set these colors and options inside the tag name:\n\n```python\n# green text\nself.line(\"<fg=green>foo</>\")\n\n# black text on a cyan background\nself.line(\"<fg=black;bg=cyan>foo</>\")\n\n# bold text on a yellow background\nself.line(\"<bg=yellow;options=bold>foo</>\")\n```\n\n### Verbosity Levels\n\nCleo has four verbosity levels. These are defined in the `Output` class:\n\n| Mode                     | Meaning                            | Console option    |\n| ------------------------ | ---------------------------------- | ----------------- |\n| `Verbosity.QUIET`        | Do not output any messages         | `-q` or `--quiet` |\n| `Verbosity.NORMAL`       | The default verbosity level        | (none)            |\n| `Verbosity.VERBOSE`      | Increased verbosity of messages    | `-v`              |\n| `Verbosity.VERY_VERBOSE` | Informative non essential messages | `-vv`             |\n| `Verbosity.DEBUG`        | Debug messages                     | `-vvv`            |\n\nIt is possible to print a message in a command for only a specific\nverbosity level. For example:\n\n```python\nif Verbosity.VERBOSE <= self.io.verbosity:\n    self.line(...)\n```\n\nThere are also more semantic methods you can use to test for each of the\nverbosity levels:\n\n```python\nif self.output.is_quiet():\n    # ...\n\nif self.output.is_verbose():\n    # ...\n```\n\nYou can also pass the verbosity flag directly to `line()`.\n\n```python\nself.line(\"\", verbosity=Verbosity.VERBOSE)\n```\n\nWhen the quiet level is used, all output is suppressed.\n\n### Using Arguments\n\nThe most interesting part of the commands are the arguments and options\nthat you can make available. Arguments are the strings - separated by\nspaces - that come after the command name itself. They are ordered, and\ncan be optional or required. For example, add an optional `last_name`\nargument to the command and make the `name` argument required:\n\n```python\nclass GreetCommand(Command):\n    name = \"greet\"\n    description = \"Greets someone\"\n    arguments = [\n        argument(\n            \"name\",\n            description=\"Who do you want to greet?\",\n        ),\n        argument(\n            \"last_name\",\n            description=\"Your last name?\",\n            optional=True\n        )\n    ]\n    options = [\n        option(\n            \"yell\",\n            \"y\",\n            description=\"If set, the task will yell in uppercase letters\",\n            flag=True\n        )\n    ]\n```\n\nYou now have access to a `last_name` argument in your command:\n\n```python\nlast_name = self.argument(\"last_name\")\nif last_name:\n    text += f\" {last_name}\"\n```\n\nThe command can now be used in either of the following ways:\n\n```bash\n$ python application.py greet John\n$ python application.py greet John Doe\n```\n\nIt is also possible to let an argument take a list of values (imagine\nyou want to greet all your friends). For this it must be specified at\nthe end of the argument list:\n\n```python\nclass GreetCommand(Command):\n    name = \"greet\"\n    description = \"Greets someone\"\n    arguments = [\n        argument(\n            \"names\",\n            description=\"Who do you want to greet?\",\n            multiple=True\n        )\n    ]\n    options = [\n        option(\n            \"yell\",\n            \"y\",\n            description=\"If set, the task will yell in uppercase letters\",\n            flag=True\n        )\n    ]\n```\n\nTo use this, just specify as many names as you want:\n\n```bash\n$ python application.py greet John Jane\n```\n\nYou can access the `names` argument as a list:\n\n```python\nnames = self.argument(\"names\")\nif names:\n    text = \"Hello \" + \", \".join(names)\n```\n\n\n### Using Options\n\nUnlike arguments, options are not ordered (meaning you can specify them\nin any order) and are specified with two dashes (e.g. `--yell` - you can\nalso declare a one-letter shortcut that you can call with a single dash\nlike `-y`). Options are _always_ optional, and can be setup to accept a\nvalue (e.g. `--dir=src`) or simply as a boolean flag without a value\n(e.g. `--yell`).\n\n> _Tip_: It is also possible to make an option _optionally_ accept a value (so\n> that `--yell` or `--yell=loud` work). Options can also be configured to\n> accept a list of values.\n\nFor example, add a new option to the command that can be used to specify\nhow many times in a row the message should be printed:\n\n```python\nclass GreetCommand(Command):\n    name = \"greet\"\n    description = \"Greets someone\"\n    arguments = [\n        argument(\n            \"name\",\n            description=\"Who do you want to greet?\",\n            optional=True\n        )\n    ]\n    options = [\n        option(\n            \"yell\",\n            \"y\",\n            description=\"If set, the task will yell in uppercase letters\",\n            flag=True\n        ),\n        option(\n            \"iterations\",\n            description=\"How many times should the message be printed?\",\n            default=1\n        )\n    ]\n```\n\nNext, use this in the command to print the message multiple times:\n\n```python\nfor _ in range(int(self.option(\"iterations\"))):\n    self.line(text)\n```\n\nNow, when you run the task, you can optionally specify a `--iterations`\nflag:\n\n```bash\n$ python application.py greet John\n$ python application.py greet John --iterations=5\n```\n\nThe first example will only print once, since `iterations` is empty and\ndefaults to `1`. The second example will print five times.\n\nRecall that options don\\'t care about their order. So, either of the\nfollowing will work:\n\n```bash\n$ python application.py greet John --iterations=5 --yell\n$ python application.py greet John --yell --iterations=5\n```\n\n\n### Testing Commands\n\nCleo provides several tools to help you test your commands. The most\nuseful one is the `CommandTester` class. It uses a special IO class to\nease testing without a real console:\n\n```python\nfrom greet_command import GreetCommand\n\nfrom cleo.application import Application\nfrom cleo.testers.command_tester import CommandTester\n\n\ndef test_execute():\n    application = Application()\n    application.add(GreetCommand())\n\n    command = application.find(\"greet\")\n    command_tester = CommandTester(command)\n    command_tester.execute()\n\n    assert \"...\" == command_tester.io.fetch_output()\n```\n\nThe `CommandTester.io.fetch_output()` method returns what would have\nbeen displayed during a normal call from the console.\n`CommandTester.io.fetch_error()` is also available to get what you have\nbeen written to the stderr.\n\nYou can test sending arguments and options to the command by passing\nthem as a string to the `CommandTester.execute()` method:\n\n```python\nfrom greet_command import GreetCommand\n\nfrom cleo.application import Application\nfrom cleo.testers.command_tester import CommandTester\n\n\ndef test_execute():\n    application = Application()\n    application.add(GreetCommand())\n\n    command = application.find(\"greet\")\n    command_tester = CommandTester(command)\n    command_tester.execute(\"John\")\n\n    assert \"John\" in command_tester.io.fetch_output()\n```\n\nYou can also test a whole console application by using the\n`ApplicationTester` class.\n\n### Calling an existing Command\n\nIf a command depends on another one being run before it, instead of\nasking the user to remember the order of execution, you can call it\ndirectly yourself. This is also useful if you want to create a \\\"meta\\\"\ncommand that just runs a bunch of other commands.\n\nCalling a command from another one is straightforward:\n\n```python\ndef handle(self):\n    return_code = self.call(\"greet\", \"John --yell\")\n    return return_code\n```\n\nIf you want to suppress the output of the executed command, you can use\nthe `call_silent()` method instead.\n\n### Autocompletion\n\nCleo supports automatic (tab) completion in `bash`, `zsh` and `fish`.\n\nBy 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):\n\n```bash\n# Bash\n[program] completions bash | sudo tee /etc/bash_completion.d/[program].bash-completion\n\n# Bash - macOS/Homebrew (requires `brew install bash-completion`)\n[program] completions bash > $(brew --prefix)/etc/bash_completion.d/[program].bash-completion\n\n# Zsh\nmkdir ~/.zfunc\necho \"fpath+=~/.zfunc\" >> ~/.zshrc\n[program] completions zsh > ~/.zfunc/_[program]\n\n# Zsh - macOS/Homebrew\n[program] completions zsh > $(brew --prefix)/share/zsh/site-functions/_[program]\n\n# Fish\n[program] completions fish > ~/.config/fish/completions/[program].fish\n```\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Cleo allows you to create beautiful and testable command-line interfaces.",
    "version": "2.2.0",
    "project_urls": {
        "Homepage": "https://github.com/python-poetry/cleo",
        "Repository": "https://github.com/python-poetry/cleo"
    },
    "split_keywords": [
        "cli",
        " commands"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b647c0045564501f1537691595010ff6f1239b2c5905427d1fa789939da1b88f",
                "md5": "3ab4cac0e4a9dc9ff52dbf8a5fe8d76b",
                "sha256": "8764a9af9ca2662fc6571c0b13bf3cfcf8994947601480f05762efa7569cda37"
            },
            "downloads": -1,
            "filename": "cleo-2.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3ab4cac0e4a9dc9ff52dbf8a5fe8d76b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.7",
            "size": 80722,
            "upload_time": "2024-11-18T12:29:31",
            "upload_time_iso_8601": "2024-11-18T12:29:31.962540Z",
            "url": "https://files.pythonhosted.org/packages/b6/47/c0045564501f1537691595010ff6f1239b2c5905427d1fa789939da1b88f/cleo-2.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8a8a2b50f680e45a17f5030395ba4e63ad20fa0ff74dee28a658239e74cd012c",
                "md5": "181d084ae0577f9aac314842d3b2a765",
                "sha256": "08f8f9c339f2a6f6965cae9aa533ff868b62e5ed4f8d8ff41d5ede25f7489628"
            },
            "downloads": -1,
            "filename": "cleo-2.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "181d084ae0577f9aac314842d3b2a765",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.7",
            "size": 81105,
            "upload_time": "2024-11-18T12:29:34",
            "upload_time_iso_8601": "2024-11-18T12:29:34.337254Z",
            "url": "https://files.pythonhosted.org/packages/8a/8a/2b50f680e45a17f5030395ba4e63ad20fa0ff74dee28a658239e74cd012c/cleo-2.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-18 12:29:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "python-poetry",
    "github_project": "cleo",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "cleo"
}
        
Elapsed time: 1.24553s