Best Python code snippet using molecule_python
cliparse.py
Source:cliparse.py  
...333        return decorator334    def alias(self, source_path, dest_path):335        scmd, spath = self._get_scmd_path(source_path)336        dcmd, dpath = self._get_scmd_path(dest_path)337        dest_cmd = copy.copy(scmd._get_subcommand(spath[-1]))338        dest_cmd.name = dpath[-1]339        dcmd.subcommands.append(dest_cmd)340    def set_default(self, parser):341        parser.values.update(self.defaults)342        for arg in self.arguments:343            arg.set_default(parser)344        for opt in self.options:345            opt.set_default(parser)346    def parse(self, tokens):347        parser = Parser(tokens)348        self._parse_command(parser)349        if parser.token:350            parser.error('Unparsed tokens: %s' % ' '.join(parser.tokens[parser.pos:]))351        return parser352    def complete(self, line, point):353        # ignore everything after point354        line = line[:point]355        # if the line ends in an incomplete escape sequence skip it356        if line[-1] == '\\' and line[-2] != '\\':357            line = line[:-1]358        quote_char = ''359        for attempt in range(2):360            try:361                lex = shlex.shlex(line, posix=True)362                lex.whitespace_split = True363                tokens = list(lex)364            except ValueError:365                if attempt == 0:366                    # close the quotes and try again367                    quote_char = lex.state368                    line += quote_char369                else:370                    raise371        tokens = tokens[1:]  # skip the program name372        if tokens and (line[-1] != ' ' or line[-2:] == '\ '):373            complete_token = tokens.pop()374        else:375            complete_token = ''376        parser = Parser(tokens, complete_token)377        self._parse_command(parser)378        return set(bash_quote(c, quote_char) for c in parser._completions)379    def handle_shell_completion(self):380        if 'COMP_LINE' in os.environ:381            for c in self.complete(os.environ['COMP_LINE'], int(os.environ['COMP_POINT'])):382                print(c)383            sys.exit()384    def usage(self):385        return ' '.join([self.name] + [a.usage() for a in self.arguments])386    def chain_usage(self, chain):387        return ' '.join(c.usage() for c in chain)388    def print_help(self, subcommands):389        '''Only works for the top-level command'''390        last = self391        chain = [self]392        for cmd_name in subcommands:393            last = last._get_subcommand(cmd_name)394            if last is None:395                print("Unknown subcommand: %s" % cmd_name)396                return397            chain.append(last)398        usage = self.chain_usage(chain)399        if last.subcommands:400            if last.default_subcommand:401                usage += ' [<subcommand>]'402            else:403                usage += ' <subcommand>'404        print("Usage: {}".format(usage))405        if last.description or last.help:406            print("\n", last.description or last.help)407        def _cmd_chains(cmd, stop_on_args=False):408            '''Follows subcommand chains until an argument can be specified'''409            if not cmd.subcommands or (cmd.arguments and stop_on_args):410                return {'': cmd}411            else:412                return dict(((s.name + ' ' + name).strip(), cmd)413                            for s in cmd.subcommands414                            for name, cmd in _cmd_chains(s, True).items())415        if last.subcommands:416            print("\nSubcommands:")417            if last.default_subcommand:418                cmd = last._get_subcommand(last.default_subcommand)419                print("  %-20s %s" % ('[%s]' % cmd.name, cmd.help or cmd.name))420            for name, cmd in sorted(_cmd_chains(last).items()):421                if not last.default_subcommand or last.default_subcommand != name:422                    print("  %-20s %s" % (name, cmd.help or name))423        for i, cmd in enumerate(reversed(chain)):424            if cmd.options:425                print("\nOptions for %s:" % ' '.join(c.name for c in chain[:len(chain) - i]))426                wrapper = textwrap.TextWrapper(width=80,427                                               initial_indent=' ' * 26,428                                               subsequent_indent=' ' * 26)429                for opt in sorted(cmd.options, key=lambda x: x.long or x.short):430                    print("  %-2s %-20s %s" % ('-' + opt.short if opt.short else '',431                                               '--' + opt.long if opt.long else '',432                                               wrapper.fill(opt.help or '').lstrip()))433    def _get_subcommand(self, subcommand):434        for cmd in self.subcommands:435            if cmd.name == subcommand:436                return cmd437        else:438            return None439    def _get_scmd_path(self, path_string):440        path = path_string.split()441        cmd = self442        for cname in path[:-1]:443            cmd = cmd._get_subcommand(cname)444            if cmd is None:445                raise Exception('Invalid command path: %s (%s not found)' % (path_string, cname))446        return cmd, path447    def _parse_command(self, parser):448        self.set_default(parser)449        parser.add_options(self.options)450        parser.parse_arguments(self.arguments)451        if self.subcommands:452            if parser._completing_argument:453                parser._add_completions(s.name for s in self.subcommands)454            token = parser.eat_token()455            if token is None:456                if self.default_subcommand:457                    self._get_subcommand(self.default_subcommand).set_default(parser)458                else:459                    parser.error("Subcommand expected")460            else:461                cmd = self._get_subcommand(token.lower())462                if cmd:463                    parser.subcommands.append(cmd.name)464                    cmd._parse_command(parser)465                elif self.default_subcommand:466                    parser.barf_token()467                    cmd = self._get_subcommand(self.default_subcommand)468                    cmd._parse_command(parser)469                else:...dispatcher.py
Source:dispatcher.py  
...44        argv = [args.get("<command>")] + args.get("<args>", default_args)45        return _run_command(argv)46    except exc.InvalidCliValueError as e:47        return str(e)48def _get_subcommand(name):49    # type: (str) -> config.RcliEntryPoint50    """Return the function for the specified subcommand.51    Args:52        name: The name of a subcommand.53    Returns:54        The loadable object from the entry point represented by the subcommand.55    """56    _LOGGER.debug('Accessing subcommand "%s".', name)57    if name not in settings.subcommands:58        raise ValueError(59            "\"{subcommand}\" is not a {command} command. '{command} help -a' "60            "lists all available subcommands.".format(61                command=settings.command, subcommand=name62            )63        )64    return settings.subcommands[name]65def _run_command(argv):66    # type: (typing.List[str]) -> typing.Any67    """Run the command with the given CLI options and exit.68    Command functions are expected to have a __doc__ string that is parseable69    by docopt.70    Args:71        argv: The list of command line arguments supplied for a command. The72            first argument is expected to be the name of the command to be run.73            Note that this is different than the full arguments parsed by74            docopt for the entire program.75    Raises:76        ValueError: Raised if the user attempted to run an invalid command.77    """78    command_name, argv = _get_command_and_argv(argv)79    _LOGGER.info(80        'Running command "%s %s" with args: %s',81        settings.command,82        command_name,83        argv,84    )85    subcommand = _get_subcommand(command_name)86    func = call.get_callable(subcommand)87    doc = usage.format_usage(subcommand.__doc__)88    args = _get_parsed_args(command_name, doc, argv)89    return call.call(func, args) or 090def _get_command_and_argv(argv):91    # type: (typing.List[str]) -> typing.Tuple[str, typing.List[str]]92    """Extract the command name and arguments to pass to docopt.93    Args:94        argv: The argument list being used to run the command.95    Returns:96        A tuple containing the name of the command and the arguments to pass97        to docopt.98    """99    command_name = argv[0]...houston.py
Source:houston.py  
...32    def get_default_subcommands(cls):33        from .subcommands._registry import SubcommandRegistry34        return SubcommandRegistry()35    def call_command(self, command, *args, **kwargs):36        subcommand = self._get_subcommand(subcommand=command)37        return self._call_subcommand(38            subcommand,39            parsed_args={},40            unparsed_args=[*args, *self._kwargs_to_unparsed_args(**kwargs)]41        )42    def _kwargs_to_unparsed_args(self, **kwargs):43        args = []44        for k, v in kwargs.items():45            args.extend(self._kvp_to_args(k=k, v=v))46        return args47    def _kvp_to_args(self, k=None, v=None):48        if isinstance(v, bool):49            args = ['--{k}'.format(k=k)]50        elif isinstance(v, list):51            args = []52            for item in v:53                args.extend(self._kvp_to_args(k=k, v=item))54        else:55            args = ['--{k}={v}'.format(k=k, v=v)]56        return args57    def _get_subcommand(self, subcommand=None):58        return self.subcommands[subcommand]59    def _call_subcommand(self, subcommand, parsed_args=None,60                         unparsed_args=None):61        return subcommand.call(houston=self, parsed_args=parsed_args,62                               unparsed_args=unparsed_args)63    def run_command(self, command, *args, **kwargs):64        subcommand = self._get_subcommand(subcommand=command)65        return self._run_subcommand(subcommand, *args, **kwargs)66    def _run_subcommand(self, subcommand=None, *args, **kwargs):67        return subcommand.run(*args, houston=self, **kwargs)68    @property...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
