Best Python code snippet using avocado_python
settings.py
Source:settings.py  
...126            if self._metavar is None:127                return self.key128        return self._metavar129    @property130    def arg_parse_args(self):131        args = {'help': self.help_msg,132                'default': None}133        if self.nargs:134            args['nargs'] = self.nargs135        if self.metavar:136            args['metavar'] = self.metavar137        if self.choices:138            args['choices'] = self.choices139        if self.action:140            args['action'] = self.action141        if self.key_type is not bool:142            # We don't specify type for bool143            args['type'] = self.argparse_type144        if not self.positional_arg:...cmdline.py
Source:cmdline.py  
1import argparse2import inspect3import os4import re5import sys6"""7easy_argparser.py8====================================9The core module of my project10"""11arg_parse_args = {12    'VERSION': '1.0.0',13    'DESCRIPTION': '',14    'PROG': os.path.basename(__file__),15}16def command_line(self):17    """18    Autogenerate command line.19    """20    methods = inspect.getmembers(self, predicate=inspect.ismethod)21    v = '%(prog)s {version}'.format(version=self.arg_parse_args['VERSION'])22    my_parser = argparse.ArgumentParser(23        formatter_class=argparse.RawDescriptionHelpFormatter,24        description=v + " - " + self.arg_parse_args['DESCRIPTION'], prog=self.arg_parse_args['PROG']25    )26    functions = [i[0] for i in methods]27    all_params = {}28    for function in functions:29        if function == 'command_line': continue30        params = inspect.signature(eval('self.' + function)).parameters.values()31        param_names = [i.name for i in params if i.default == inspect._empty]32        optionals = [(i.name, i.default) for i in params if i.default != inspect._empty]33        all_params[function] = [param_names, optionals]34        if optionals or len(param_names) > 0:35            my_parser.add_argument("--" + function,36                                   nargs="*" if optionals else len(param_names) if len(param_names) > 0 else None,37                                   metavar=tuple(param_names) if param_names and not optionals38                                   else (' '.join(param_names), "") if param_names and optionals else None,39                                   help="Optional args: " + " ".join(["[{0}={1}]".format(*p)40                                                                      if p[1] else "[{0}]".format(p[0])41                                                                      for p in optionals])42                                   if len(optionals) > 0 else None)43        else:44            my_parser.add_argument('--' + function, action='store_true')45    args = my_parser.parse_args()46    for arg, value in args.__dict__.items():47        if len(all_params[arg][0]) == 0 and len(all_params[arg][1]) == 0 and not value:48            value = None49        if arg in functions and value is not None:50            self.called_function = function51            try:52                if len(all_params[arg][0]) == 0 and len(all_params[arg][1]) == 0:53                    res = eval('self.{0}()'.format(arg))54                else:55                    res = eval('self.' + arg)(*value)56            except Exception as e:57                raise e58            # exit(0)59def add_argparser():60    return True61# Ignore decorator to ignore a method class or variable62# decorator63def Cmdline(options):64    """65    Decorator to autogenerate command line.66    """67    def _cmdline(func):68        def wrapper(*inner_args, **kwargs):69            # print(enter_string)70            if options:71                arg_parse_args.update(options)72            setattr(func, 'arg_parse_args', arg_parse_args)73            setattr(func, 'command_line', command_line)74            return func(*inner_args, **kwargs)75            # print(exit_string)76        # if not inspect.isclass(func): raise Exception("Can only decorate classes")77        return wrapper78    return _cmdline79def cmdline(obj=None, options=None):80    """81    Call this to make your file a cmdline program82    :param obj:83    :param options:84    :return:85    """86    if not obj:87        modules = sys.modules.keys()88        obj = [i for i in globals() if i not in modules and not re.match('__.*__', i)]89        print(obj)90if __name__ == '__main__':91    # a = inspect.getmembers()92    # a = [func for func in dir()]93    # print(a)94    # print(sys.modules.keys())95    cmdline()96#97# @cmdline(OPTIONS={98#     'DESCRIPTION': 'description test'99# })100# class A:101#     a = 'something'102#103#     def imcool(self):104#         print('i"m cool')105#106#     def say(self, something):107#         print(something)108#109#...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!!
