| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
""" User registers commands with CommandGroups """ |
| 4 |
|
| 5 |
import os |
| 6 |
import sys |
| 7 |
from collections import OrderedDict |
| 8 |
|
| 9 |
from knack import CLI |
| 10 |
from knack.commands import CLICommandsLoader, CommandGroup |
| 11 |
from knack.arguments import ArgumentsContext |
| 12 |
from knack.help import CLIHelp |
| 13 |
|
| 14 |
from knack.help_files import helps |
| 15 |
|
| 16 |
cli_name = os.path.basename(__file__) |
| 17 |
|
| 18 |
helps['abc'] = """ |
| 19 |
type: group |
| 20 |
short-summary: Manage the alphabet of words. |
| 21 |
""" |
| 22 |
|
| 23 |
helps['abc list'] = """ |
| 24 |
type: command |
| 25 |
short-summary: List the alphabet. |
| 26 |
examples: |
| 27 |
- name: It's pretty straightforward. |
| 28 |
text: {cli_name} abc list |
| 29 |
""".format(cli_name=cli_name) |
| 30 |
|
| 31 |
|
| 32 |
def a_test_command_handler(): |
| 33 |
return [{'a': 1, 'b': 1234}, {'a': 3, 'b': 4}] |
| 34 |
|
| 35 |
|
| 36 |
def abc_list_command_handler(): |
| 37 |
import string |
| 38 |
return list(string.ascii_lowercase) |
| 39 |
|
| 40 |
|
| 41 |
def hello_command_handler(myarg=None, abc=None): |
| 42 |
return ['hello', 'world', myarg, abc] |
| 43 |
|
| 44 |
WELCOME_MESSAGE = r""" |
| 45 |
_____ _ _____ |
| 46 |
/ ____| | |_ _| |
| 47 |
| | | | | | |
| 48 |
| | | | | | |
| 49 |
| |____| |____ _| |_ |
| 50 |
\_____|______|_____| |
| 51 |
|
| 52 |
|
| 53 |
Welcome to the cool new CLI! |
| 54 |
""" |
| 55 |
|
| 56 |
|
| 57 |
class MyCLIHelp(CLIHelp): |
| 58 |
|
| 59 |
def __init__(self, cli_ctx=None): |
| 60 |
super(MyCLIHelp, self).__init__(cli_ctx=cli_ctx, |
| 61 |
privacy_statement='My privacy statement.', |
| 62 |
welcome_message=WELCOME_MESSAGE) |
| 63 |
|
| 64 |
|
| 65 |
class MyCommandsLoader(CLICommandsLoader): |
| 66 |
|
| 67 |
def load_command_table(self, args): |
| 68 |
with CommandGroup(self, 'hello', '__main__#{}') as g: |
| 69 |
g.command('world', 'hello_command_handler', confirmation=True) |
| 70 |
with CommandGroup(self, 'abc', '__main__#{}') as g: |
| 71 |
g.command('list', 'abc_list_command_handler') |
| 72 |
g.command('show', 'a_test_command_handler') |
| 73 |
return super(MyCommandsLoader, self).load_command_table(args) |
| 74 |
|
| 75 |
def load_arguments(self, command): |
| 76 |
with ArgumentsContext(self, 'hello world') as ac: |
| 77 |
ac.argument('myarg', type=int, default=100) |
| 78 |
super(MyCommandsLoader, self).load_arguments(command) |
| 79 |
|
| 80 |
|
| 81 |
mycli = CLI(cli_name=cli_name, |
| 82 |
config_dir=os.path.expanduser(os.path.join('~', '.{}'.format(cli_name))), |
| 83 |
config_env_var_prefix=cli_name, |
| 84 |
commands_loader_cls=MyCommandsLoader, |
| 85 |
help_cls=MyCLIHelp) |
| 86 |
exit_code = mycli.invoke(sys.argv[1:]) |
| 87 |
sys.exit(exit_code) |