File: commands.md

package info (click to toggle)
knack 0.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 696 kB
  • sloc: python: 6,261; sh: 8; makefile: 4
file content (42 lines) | stat: -rw-r--r-- 1,782 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Commands
========

The commands loader contains a command table.
A command table is a dictionary from command name to a `CLICommand` instance.

**Writing a Command**

Write your command as a simple function, specifying your arguments as the parameter names.

When choosing names, it is recommended that you look at similar commands and follow those naming conventions to take advantage of any aliasing that may already be in place.

If you specify a default value in your function signature, this will flag the argument as optional and will automatically display the default value in the help text for the command. Any parameters that do not have a default value are required and will automatically appear in help with the [Required] label. The required and default behaviors for arguments can be overridden if needed with the `ArgumentsContext` function but this is not generally needed.

There are a few different ways to register commands (see the examples directory for working samples).
Typically, you would use `CommandGroup` to register commands.

For example:

```Python
def hello_command_handler():
    return ['hello', 'world']

class MyCommandsLoader(CLICommandsLoader):

    def load_command_table(self, args):
        with CommandGroup(__name__, self, 'hello', '__main__#{}') as g:
            g.command('world', 'hello_command_handler')
        return OrderedDict(self.command_table)

mycli = CLI(cli_name='mycli', commands_loader_cls=MyCommandsLoader)
exit_code = mycli.invoke(sys.argv[1:])
```

You can also provide your own command class to the CLICommandsLoader like so:

```Python
class MyCommandsLoader(CLICommandsLoader):

    def __init__(self, cli_ctx=None):
        super(MyCommandsLoader, self).__init__(cli_ctx=cli_ctx, command_cls=MyCustomCLICommand)
```