Juju CLI subcommand for dispatching resources subcommands.
517464
def resources(argv=sys.argv[1:]):
    
    eps = iter_entry_points('jujuresources.subcommands')
    ep_map = {ep.name: ep.load() for ep in eps}

    parser = argparse.ArgumentParser()
    if '--description' in argv:
        print('Manage and mirror charm resources')
        return 0

    subparsers = {}
    subparser_factory = parser.add_subparsers()
    subparsers['help'] = subparser_factory.add_parser('help', help='Display help for a subcommand')
    subparsers['help'].add_argument('command', nargs='?')
    subparsers['help'].set_defaults(subcommand='help')
    for name, subcommand in ep_map.items():
        subparsers[name] = subparser_factory.add_parser(name, help=subcommand.__doc__)
        subparsers[name].set_defaults(subcommand=subcommand)
        for args, kwargs in getattr(subcommand, '_subcommand_args', []):
            subparsers[name].add_argument(*args, **kwargs)
        for argset in getattr(subcommand, '_subcommand_argsets', {}).values():
            group = subparsers[name].add_mutually_exclusive_group(required=True)
            for args, kwargs in argset:
                group.add_argument(*args, **kwargs)
    opts = parser.parse_args(argv)
    if opts.subcommand == 'help':
        if opts.command:
            subparsers[opts.command].print_help()
        else:
            parser.print_help()
    else:
        return _exit(opts.subcommand(opts) or 0)
1033659
def load_commands(cli, manage_dict):
    """"""
    namespaced = manage_dict.get('namespaced')

    # get click commands
    commands = manage_dict.get('click_commands', [])
    for command_dict in commands:
        root_module = import_string(command_dict['module'])
        group = cli.manage_groups.get(command_dict.get('group'), cli)
        if getattr(root_module, '__path__', None):
            # This is a package
            iter_modules = pkgutil.iter_modules(
                root_module.__path__, prefix=root_module.__name__ + '.'
            )
            submodules_names = [item[1] for item in iter_modules]
            submodules = [import_string(name) for name in submodules_names]
            for module in submodules:
                add_click_commands(module, group, command_dict, namespaced)
        else:
            # a single file module
            add_click_commands(root_module, group, command_dict, namespaced)

    # get inline commands
    commands = manage_dict.get('inline_commands', [])
    for command_dict in commands:
        name = command_dict['name']
        help_text = command_dict.get('help_text')
        options = command_dict.get('options', {})
        arguments = command_dict.get('arguments', {})
        context = command_dict.get('context', [])
        code = command_dict['code']
        group = cli.manage_groups.get(command_dict.get('group'), cli)
        group.add_command(
            make_command_from_string(
                code=code,
                cmd_context=get_context(context),
                options=options,
                arguments=arguments,
                help_text=help_text
            ),
            name=name
        )

    # get function commands
    commands = manage_dict.get('function_commands', [])
    for command_dict in commands:
        name = command_dict['name']
        help_text = command_dict.get('help_text')
        options = command_dict.get('options', {})
        arguments = command_dict.get('arguments', {})
        function = import_string(command_dict['function'])
        group = cli.manage_groups.get(command_dict.get('group'), cli)
        group.add_command(
            make_command_from_function(
                function=function,
                options=options,
                arguments=arguments,
                help_text=help_text
            ),
            name=name
        )
686130
def cli(ctx, env):
    """"""
    env.out("Welcome to the SoftLayer shell.")
    env.out("")

    formatter = formatting.HelpFormatter()
    commands = []
    shell_commands = []
    for name in cli_core.cli.list_commands(ctx):
        command = cli_core.cli.get_command(ctx, name)
        if command.short_help is None:
            command.short_help = command.help
        details = (name, command.short_help)
        if name in dict(routes.ALL_ROUTES):
            shell_commands.append(details)
        else:
            commands.append(details)

    with formatter.section('Shell Commands'):
        formatter.write_dl(shell_commands)

    with formatter.section('Commands'):
        formatter.write_dl(commands)

    for line in formatter.buffer:
        env.out(line, newline=False)
410954
def cli(ctx, resource):
    
    log = logging.getLogger('ipsv.setup')
    assert isinstance(ctx, Context)

    resource = str(resource).lower()

    if resource == 'ips':
        resource = IpsManager(ctx)
        for r in resource.versions.values():
            click.secho(r.version.vstring, bold=True)
        return

    if resource in ('dev_tools', 'dev tools'):
        resource = DevToolsManager(ctx)
        for r in resource.versions.values():
            click.secho('{v} ({id})'.format(v=r.version.vstring, id=r.version.vid), bold=True)
        return
164757
def load_subcommand(subparsers):
    """"""
    parser_start = subparsers.add_parser('start', help='Start uwsgi-sloth process for realtime analyzing.')
    parser_start.add_argument('-c', '--config', type=argparse.FileType('r'), dest='config',
                                help='uwsgi-sloth config file, use "uwsgi-sloth echo_conf" for a default one', required=True)
    parser_start.set_defaults(func=start)
1279720
def _WorkerCommand_launcher(self):
        """"""
        return [
            self.workersArguments.pythonExecutable,
            '-m',
            'scoop.launch.__main__',
            str(self.workerAmount),
            str(self.workersArguments.verbose),
        ]
972749
def jupytext_cli(args=None):
    """"""
    try:
        jupytext(args)
    except (ValueError, TypeError, IOError) as err:
        sys.stderr.write('[jupytext] Error: ' + str(err) + '\n')
        exit(1)
749532
def _queue(self, kwargs):
    """"""
    if not 'hard resource_list' in kwargs: return 'all.q'
    d = dict([k.split('=') for k in kwargs['hard resource_list'].split(',')])
    for k in d:
      if k[0] == 'q' and d[k] == 'TRUE': return k
    return 'all.q'
1123314
def load_subcommand(subparsers):
    
    parser_analyze = subparsers.add_parser('analyze', help='Analyze uwsgi log to get report')
    parser_analyze.add_argument('-f', '--filepath', type=argparse.FileType('r'), dest='filepath',
                                help='Path of uwsgi log file', required=True)
    parser_analyze.add_argument('--output', dest="output", type=argparse.FileType('w'), default=sys.stdout, 
                                help='HTML report file path')
    parser_analyze.add_argument('--min-msecs', dest="min_msecs", type=int, default=200,
                                help='Request serve time lower than this value will not be counted, default: 200')
    parser_analyze.add_argument('--domain', dest="domain", type=str, required=False,
                                help='Make url in report become a hyper-link by settings a domain')
    parser_analyze.add_argument('--url-file', dest="url_file", type=argparse.FileType('r'), required=False, 
                                help='Customized url rules in regular expression')
    parser_analyze.add_argument('--limit-url-groups', dest="limit_url_groups", type=int, required=False, 
                                default=LIMIT_URL_GROUPS, help='Number of url groups considered, default: 200')
    parser_analyze.add_argument('--limit-per-url-group', dest="limit_per_url_group", type=int,
                                required=False, default=LIMIT_PER_URL_GROUP,
                                help='Number of urls per group considered, default: 20')
    parser_analyze.set_defaults(func=analyze)
1049046
def _dispatch_command(reactor, cfg, command):
    
    cfg.timing.add("command dispatch")
    cfg.timing.add(
        "import", when=start, which="top").finish(when=top_import_finish)

    try:
        yield maybeDeferred(command)
    except (WrongPasswordError, NoTorError) as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=cfg.stderr)
        raise SystemExit(1)
    except (WelcomeError, UnsendableFileError, KeyFormatError) as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=cfg.stderr)
        print(six.u(""), file=cfg.stderr)
        print(six.text_type(e), file=cfg.stderr)
        raise SystemExit(1)
    except TransferError as e:
        print(u"TransferError: %s" % six.text_type(e), file=cfg.stderr)
        raise SystemExit(1)
    except ServerConnectionError as e:
        msg = fill("ERROR: " + dedent(e.__doc__)) + "\n"
        msg += "(relay URL was %s)\n" % e.url
        msg += six.text_type(e)
        print(msg, file=cfg.stderr)
        raise SystemExit(1)
    except Exception as e:
        # this prints a proper traceback, whereas
        # traceback.print_exc() just prints a TB to the "yield"
        # line above ...
        Failure().printTraceback(file=cfg.stderr)
        print(u"ERROR:", six.text_type(e), file=cfg.stderr)
        raise SystemExit(1)

    cfg.timing.add("exit")
    if cfg.dump_timing:
        cfg.timing.write(cfg.dump_timing, cfg.stderr)
558649
def foreach(self, argv, func):
        """"""
        opts = cmdline(argv)
        if len(opts.args) == 0:
            error("Command requires an index name", 2)
        for name in opts.args:
            if name not in self.service.indexes:
                error("Index '%s' does not exist" % name, 2)
            index = self.service.indexes[name]
            func(index)
675155
def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]:
    """"""
    sub_cmds = []

    # Check if this is parser has sub-commands
    if parser is not None and parser._subparsers is not None:

        # Find the _SubParsersAction for the sub-commands of this parser
        for action in parser._subparsers._actions:
            if isinstance(action, argparse._SubParsersAction):
                for sub_cmd, sub_cmd_parser in action.choices.items():
                    sub_cmds.append(sub_cmd)

                    # Look for nested sub-commands
                    for nested_sub_cmd in get_sub_commands(sub_cmd_parser):
                        sub_cmds.append('{} {}'.format(sub_cmd, nested_sub_cmd))

                break

    sub_cmds.sort()
    return sub_cmds
1136111
function commands(req, res /*, next */) {
  req.app.commands.forEach(function(command) {
    res.writeln(command);
  });
  res.end();
}
1098447
def subprocess(cls, cmd, **kwargs):
    
    def call(args):
      return subprocess.call(cmd + args, **kwargs)
    return cls(call)
203368
def topic_command():
    '''
    '''
    parser = argparse.ArgumentParser(description='json pub/sub tool')
    pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False)
    sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False)
    command_parsers = parser.add_subparsers(dest='command', help='command')

    pub_parser = command_parsers.add_parser(
        'pub', help='publish topic from command line', parents=[pub_common_parser])
    pub_parser.add_argument('topic_name', type=str, help='name of topic')
    pub_parser.add_argument(
        'data', type=str, help='json string data to be published')
    pub_parser.add_argument('--repeat', '-r', help='repeat in hz', type=float)

    echo_parser = command_parsers.add_parser(
        'echo', help='show topic data', parents=[sub_common_parser])
    echo_parser.add_argument('topic_name', type=str, help='name of topic')
    echo_parser.add_argument(
        '--num', '-n', help='print N times and exit', type=int,
        default=None)

    list_parser = command_parsers.add_parser(
        'list', help='show topic list', parents=[sub_common_parser])
    list_parser.add_argument(
        '--timeout', '-t', help='timeout in sec', type=float,
        default=1.0)

    record_parser = command_parsers.add_parser(
        'record', help='record topic data', parents=[sub_common_parser])
    record_parser.add_argument('topic_names', nargs='*',
                               help='topic names to be recorded', type=str)
    record_parser.add_argument(
        '--file', '-f', help='output file name (default: record.json)',
        type=str, default='record.json')

    play_parser = command_parsers.add_parser(
        'play', help='play recorded topic data', parents=[pub_common_parser])
    play_parser.add_argument('file', type=str, help='input file name')

    args = parser.parse_args()

    if args.command == 'pub':
        pub(args.topic_name, args.data, repeat_rate=args.repeat,
            host=args.host, pub_port=args.publisher_port)
    elif args.command == 'echo':
        echo(args.topic_name, args.num,
             host=args.host, sub_port=args.subscriber_port)
    elif args.command == 'list':
        show_list(args.timeout, host=args.host, sub_port=args.subscriber_port)
    elif args.command == 'record':
        record(args.file, args.topic_names,
               host=args.host, sub_port=args.subscriber_port)
    elif args.command == 'play':
        play(args.file, host=args.host, pub_port=args.publisher_port)
    else:
        parser.print_help()
69835
def load_cli(subparsers):
    """"""
    for command_name in available_commands():
        module = '{}.{}'.format(__package__, command_name)
        loader, description = _import_loader(module)
        parser = subparsers.add_parser(command_name,
                                       description=description)
        command = loader(parser)
        if command is None:
            raise RuntimeError('Failed to load "{}".'.format(command_name))
        parser.set_defaults(cmmd=command)
1182731
def cli():
    """"""
    args = docopt.docopt(__doc__, version=__VERSION__)
    secure = args['--secure']
    numberofwords = int(args['<numberofwords>'])

    dictpath = args['--dict']
    if dictpath is not None:
        dictfile = open(dictpath)
    else:
        dictfile = load_stream('words.txt')
    with dictfile:
        wordlist = read_wordlist(dictfile)

    words = generate_words(numberofwords, wordlist, secure=secure)
    print(' '.join(words))