Python argparse.ZERO_OR_MORE Examples

The following are 21 code examples of argparse.ZERO_OR_MORE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: test_argparse_custom.py    From cmd2 with MIT License 6 votes vote down vote up
def test_apcustom_narg_tuple_zero_base():
    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(0,))
    assert arg.nargs == argparse.ZERO_OR_MORE
    assert arg.nargs_range is None
    assert "[arg [...]]" in parser.format_help()

    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(0, 1))
    assert arg.nargs == argparse.OPTIONAL
    assert arg.nargs_range is None
    assert "[arg]" in parser.format_help()

    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(0, 3))
    assert arg.nargs == argparse.ZERO_OR_MORE
    assert arg.nargs_range == (0, 3)
    assert "arg{0..3}" in parser.format_help()


# noinspection PyUnresolvedReferences 
Example #2
Source File: cliutils.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def prepare_playbook_plugin():
    @configure
    def main():
        parser = argparse.ArgumentParser(
            description="Prepare playbook plugins"
        )
        parser.add_argument(
            "plugin_name",
            nargs=argparse.ZERO_OR_MORE,
            default=[],
            help="Namespace of plugin to prepare. Empty means all plugins"
        )
        args = parser.parse_args()

        plugs = plugins.get_playbook_plugins()
        if args.plugin_name:
            plugs = {k: v for k, v in plugs.items() if k in args.plugin_name}
        plugs = {k: v() for k, v in plugs.items()}

        for name, plug in sorted(plugs.items()):
            LOG.info("Prepare plugin %s", name)
            plug.prepare_plugin()

    return main() 
Example #3
Source File: custom_help_formatter.py    From SqueezeMeta with GNU General Public License v3.0 6 votes vote down vote up
def _get_help_string(self, action):
        """Place default value in help string."""
        h = action.help
        if '%(default)' not in action.help:
            if action.default != '' and action.default != [] and action.default is not None and type(action.default) != bool:
                if action.default is not argparse.SUPPRESS:
                    defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]

                    if action.option_strings or action.nargs in defaulting_nargs:
                        if '\n' in h:
                            lines = h.splitlines()
                            lines[0] += ' (default: %(default)s)'
                            h = '\n'.join(lines)
                        else:
                            h += ' (default: %(default)s)'
            return h 
Example #4
Source File: __init__.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        # pylint: disable=redefined-builtin
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one running domain'
            elif nargs == 1:
                help = 'running domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more running domains'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more running domains'
            elif nargs > 1:
                help = '%s running domains' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))
        super(RunningVmNameAction, self).__init__(
            option_strings, dest=dest, help=help, nargs=nargs, **kwargs) 
Example #5
Source File: __init__.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one domain name'
            elif nargs == 1:
                help = 'a domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more domain names'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more domain names'
            elif nargs > 1:
                help = '%s domain names' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))

        super(VmNameAction, self).__init__(option_strings, dest=dest, help=help,
                                           nargs=nargs, **kwargs) 
Example #6
Source File: argparse_custom.py    From cmd2 with MIT License 6 votes vote down vote up
def _format_args(self, action, default_metavar) -> str:
        get_metavar = self._metavar_formatter(action, default_metavar)
        # Begin cmd2 customization (less verbose)
        nargs_range = getattr(action, ATTR_NARGS_RANGE, None)

        if nargs_range is not None:
            if nargs_range[1] == constants.INFINITY:
                range_str = '{}+'.format(nargs_range[0])
            else:
                range_str = '{}..{}'.format(nargs_range[0], nargs_range[1])

            result = '{}{{{}}}'.format('%s' % get_metavar(1), range_str)
        elif action.nargs == ZERO_OR_MORE:
            result = '[%s [...]]' % get_metavar(1)
        elif action.nargs == ONE_OR_MORE:
            result = '%s [...]' % get_metavar(1)
        elif isinstance(action.nargs, int) and action.nargs > 1:
            result = '{}{{{}}}'.format('%s' % get_metavar(1), action.nargs)
        # End cmd2 customization
        else:
            result = super()._format_args(action, default_metavar)
        return result


# noinspection PyCompatibility 
Example #7
Source File: custom_help_formatter.py    From GTDBTk with GNU General Public License v3.0 6 votes vote down vote up
def _get_help_string(self, action):
        """Place default value in help string."""
        h = action.help
        if '%(default)' not in action.help:
            if action.default != '' and action.default != [] and \
                    action.default is not None and \
                    not isinstance(type(action.default), bool):
                if action.default is not argparse.SUPPRESS:
                    defaulting_nargs = [
                        argparse.OPTIONAL, argparse.ZERO_OR_MORE]

                    if action.option_strings or action.nargs in defaulting_nargs:
                        if '\n' in h:
                            lines = h.splitlines()
                            lines[0] += ' (default: %(default)s)'
                            h = '\n'.join(lines)
                        else:
                            h += ' (default: %(default)s)'
            return h 
Example #8
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        # pylint: disable=redefined-builtin
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one running domain'
            elif nargs == 1:
                help = 'running domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more running domains'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more running domains'
            elif nargs > 1:
                help = '%s running domains' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))
        super(RunningVmNameAction, self).__init__(
            option_strings, dest=dest, help=help, nargs=nargs, **kwargs) 
Example #9
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one domain name'
            elif nargs == 1:
                help = 'a domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more domain names'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more domain names'
            elif nargs > 1:
                help = '%s domain names' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))

        super(VmNameAction, self).__init__(option_strings, dest=dest, help=help,
                                           nargs=nargs, **kwargs) 
Example #10
Source File: detect_tls.py    From roca with MIT License 6 votes vote down vote up
def init_parser(self):
        """
        Init command line parser
        :return:
        """
        parser = argparse.ArgumentParser(description='ROCA TLS Fingerprinter')

        parser.add_argument('--debug', dest='debug', default=False, action='store_const', const=True,
                            help='Debugging logging')

        parser.add_argument('--dump', dest='dump', default=False, action='store_const', const=True,
                            help='Dump all processed info')

        parser.add_argument('--flatten', dest='flatten', default=False, action='store_const', const=True,
                            help='Flatten the dump')

        parser.add_argument('--indent', dest='indent', default=False, action='store_const', const=True,
                            help='Indent the dump')

        parser.add_argument('--hosts', dest='hosts', default=False, action='store_const', const=True,
                            help='Arguments are host names not file names')

        parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[],
                            help='files to process')
        return parser 
Example #11
Source File: argparse_completer.py    From WebPocket with GNU General Public License v3.0 5 votes vote down vote up
def _format_args(self, action, default_metavar) -> str:
        get_metavar = self._metavar_formatter(action, default_metavar)
        # Begin cmd2 customization (less verbose)
        if isinstance(action, _RangeAction) and \
                action.nargs_min is not None and action.nargs_max is not None:
            result = '{}{{{}..{}}}'.format('%s' % get_metavar(1), action.nargs_min, action.nargs_max)
        elif action.nargs == ZERO_OR_MORE:
            result = '[%s [...]]' % get_metavar(1)
        elif action.nargs == ONE_OR_MORE:
            result = '%s [...]' % get_metavar(1)
        # End cmd2 customization
        else:
            result = super()._format_args(action, default_metavar)
        return result 
Example #12
Source File: params.py    From ParlAI with MIT License 5 votes vote down vote up
def _get_help_string(self, action):
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
        if (
            hasattr(action, 'recommended')
            and action.recommended
            and action.recommended != action.default
        ):
            help += '(recommended: %(recommended)s)'
            help = help.replace(')(recommended', ', recommended')
        return help 
Example #13
Source File: argx.py    From aiven-client with Apache License 2.0 5 votes vote down vote up
def _get_help_string(self, action):
        help_text = action.help
        if '%(default)' not in action.help and action.default is not argparse.SUPPRESS:
            if action.option_strings or action.nargs in [argparse.OPTIONAL, argparse.ZERO_OR_MORE]:
                if (
                        (not isinstance(action.default, bool) and isinstance(action.default, int))
                        or (isinstance(action.default, str) and action.default)
                ):
                    help_text += ' (default: %(default)s)'
        return help_text 
Example #14
Source File: CLI.py    From ColorWallpaper with GNU General Public License v3.0 5 votes vote down vote up
def _get_help_string(self, action):
        self.default = None

        if action.default not in (None, argparse.SUPPRESS):
            if action.option_strings or action.nargs in (argparse.OPTIONAL, argparse.ZERO_OR_MORE):
                self.default = self.__format_map.get(action.dest, lambda s: s)(action.default)

        return action.help 
Example #15
Source File: tune.py    From fastchess with GNU General Public License v3.0 5 votes vote down vote up
def _get_help_string(self, action):
        help = action.help
        if not action.default:
            return help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
        return help 
Example #16
Source File: argparse_completer.py    From cmd2 with MIT License 5 votes vote down vote up
def __init__(self, arg_action: argparse.Action) -> None:
        self.action = arg_action
        self.min = None
        self.max = None
        self.count = 0
        self.is_remainder = (self.action.nargs == argparse.REMAINDER)

        # Check if nargs is a range
        nargs_range = getattr(self.action, ATTR_NARGS_RANGE, None)
        if nargs_range is not None:
            self.min = nargs_range[0]
            self.max = nargs_range[1]

        # Otherwise check against argparse types
        elif self.action.nargs is None:
            self.min = 1
            self.max = 1
        elif self.action.nargs == argparse.OPTIONAL:
            self.min = 0
            self.max = 1
        elif self.action.nargs == argparse.ZERO_OR_MORE or self.action.nargs == argparse.REMAINDER:
            self.min = 0
            self.max = constants.INFINITY
        elif self.action.nargs == argparse.ONE_OR_MORE:
            self.min = 1
            self.max = constants.INFINITY
        else:
            self.min = self.action.nargs
            self.max = self.action.nargs


# noinspection PyProtectedMember 
Example #17
Source File: argument_parsing.py    From ClusterRunner with Apache License 2.0 5 votes vote down vote up
def _get_help_string(self, action):
        """
        Appends the default argument value to the help string for non-required args that have default values.

        This implementation is loosely based off of the argparse.ArgumentDefaultsHelpFormatter.
        """
        help_string = action.help
        if not action.required:
            if action.default not in (argparse.SUPPRESS, None):
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    # using old string formatting style here because argparse internals use that
                    help_string += ' (default: %(default)s)'
        return help_string 
Example #18
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, want_app=True, want_app_no_instance=False,
                 want_force_root=False, vmname_nargs=None, **kwargs):

        super(QubesArgumentParser, self).__init__(**kwargs)

        self._want_app = want_app
        self._want_app_no_instance = want_app_no_instance
        self._want_force_root = want_force_root
        self._vmname_nargs = vmname_nargs
        if self._want_app:
            self.add_argument('--qubesxml', metavar='FILE', action='store',
                              dest='app', help=argparse.SUPPRESS)
            self.add_argument('--offline-mode', action='store_true',
                default=None, dest='offline_mode', help=argparse.SUPPRESS)


        self.add_argument('--verbose', '-v', action='count',
                          help='increase verbosity')

        self.add_argument('--quiet', '-q', action='count',
                          help='decrease verbosity')

        if self._want_force_root:
            self.add_argument('--force-root', action='store_true',
                              default=False, help='force to run as root')

        if self._vmname_nargs in [argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE]:
            vm_name_group = VmNameGroup(self, self._vmname_nargs)
            self._mutually_exclusive_groups.append(vm_name_group)
        elif self._vmname_nargs is not None:
            self.add_argument('VMNAME', nargs=self._vmname_nargs,
                              action=VmNameAction)

        self.set_defaults(verbose=1, quiet=0) 
Example #19
Source File: __init__.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, want_app=True, want_app_no_instance=False,
                 vmname_nargs=None, **kwargs):

        super(QubesArgumentParser, self).__init__(add_help=False, **kwargs)

        self._want_app = want_app
        self._want_app_no_instance = want_app_no_instance
        self._vmname_nargs = vmname_nargs
        if self._want_app:
            self.add_argument('--qubesxml', metavar='FILE', action='store',
                              dest='app', help=argparse.SUPPRESS)
            self.add_argument('--offline-mode', action='store_true',
                default=None, dest='offline_mode', help=argparse.SUPPRESS)


        self.add_argument('--verbose', '-v', action='count',
                          help='increase verbosity')

        self.add_argument('--quiet', '-q', action='count',
                          help='decrease verbosity')

        self.add_argument('--force-root', action='store_true',
                          default=False, help=argparse.SUPPRESS)

        self.add_argument('--help', '-h', action=SubParsersHelpAction,
                          help='show this help message and exit')

        if self._vmname_nargs in [argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE]:
            vm_name_group = VmNameGroup(self,
                required=(self._vmname_nargs
                          not in [argparse.ZERO_OR_MORE, argparse.OPTIONAL]))
            self._mutually_exclusive_groups.append(vm_name_group)
        elif self._vmname_nargs is not None:
            self.add_argument('VMNAME', nargs=self._vmname_nargs,
                              action=VmNameAction)

        self.set_defaults(verbose=1, quiet=0) 
Example #20
Source File: pipelineWrapper.py    From protect with Apache License 2.0 5 votes vote down vote up
def _get_help_string(self, action):
        '''
        This module was taken from the RawDescriptionHelpFormatter class
        within argparse.  It deals with the formatting of the description string
        and allows properly formatted descriptions ot be printed without line
        wrapping.
        '''
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
        return help 
Example #21
Source File: customHelpFormatter.py    From SqueezeMeta with GNU General Public License v3.0 5 votes vote down vote up
def _get_help_string(self, action):
        h = action.help
        if '%(default)' not in action.help:
            if action.default != '' and action.default != [] and action.default != None and action.default != False:
                if action.default is not argparse.SUPPRESS:
                    defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]

                    if action.option_strings or action.nargs in defaulting_nargs:
                        if '\n' in h:
                            lines = h.splitlines()
                            lines[0] += ' (default: %(default)s)'
                            h = '\n'.join(lines)
                        else:
                            h += ' (default: %(default)s)'
            return h