Python argparse.ZERO_OR_MORE() Examples

The following are code examples for showing how to use argparse.ZERO_OR_MORE(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: hat   Author: heemayl   File: client.py    GNU General Public License v3.0 6 votes vote down vote up
def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs is None:
            result = '%s' % get_metavar(1)
        elif action.nargs == argparse.OPTIONAL:
            result = '[%s]' % get_metavar(1)
        elif action.nargs == argparse.ZERO_OR_MORE:
            result = '[%s [%s ...]]' % get_metavar(2)
        # Here...
        elif action.nargs == argparse.ONE_OR_MORE:
            result = '%s' % get_metavar(1)
        elif action.nargs == argparse.REMAINDER:
            result = '...'
        elif action.nargs == argparse.PARSER:
            result = '%s ...' % get_metavar(1)
        else:
            formats = ['%s' for _ in range(action.nargs)]
            result = ' '.join(formats) % get_metavar(action.nargs)
        return result 
Example 2
Project: biolib   Author: dparks1134   File: custom_help_formatter.py    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) != types.BooleanType:
                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 3
Project: roca   Author: crocs-muni   File: detect_tls.py    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 4
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    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 5
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    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 6
Project: management-api   Author: rancher   File: my_argparse.py    Apache License 2.0 6 votes vote down vote up
def action_is_satisfied(action):
    ''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
        return True
    if action.nargs == ONE_OR_MORE:
        return num_consumed_args >= 1
    if action.nargs == PARSER:
        # Not sure what this should be, but this previously always returned False
        # so at least this won't break anything that wasn't already broken.
        return False
    if action.nargs is None:
        return num_consumed_args == 1

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args == action.nargs 
Example 7
Project: management-api   Author: rancher   File: my_argparse.py    Apache License 2.0 6 votes vote down vote up
def action_is_satisfied(action):
    ''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
        return True
    if action.nargs == ONE_OR_MORE:
        return num_consumed_args >= 1
    if action.nargs == PARSER:
        # Not sure what this should be, but this previously always returned False
        # so at least this won't break anything that wasn't already broken.
        return False
    if action.nargs is None:
        return num_consumed_args == 1

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args == action.nargs 
Example 8
Project: cmd2   Author: python-cmd2   File: test_argparse_custom.py    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 9
Project: cmd2   Author: python-cmd2   File: argparse_custom.py    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] == 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 10
Project: iiita-updates   Author: mrsaicharan1   File: my_argparse.py    Apache License 2.0 6 votes vote down vote up
def action_is_satisfied(action):
    ''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
        return True
    if action.nargs == ONE_OR_MORE:
        return num_consumed_args >= 1
    if action.nargs == PARSER:
        # Not sure what this should be, but this previously always returned False
        # so at least this won't break anything that wasn't already broken.
        return False
    if action.nargs is None:
        return num_consumed_args == 1

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args == action.nargs 
Example 11
Project: fastchess   Author: thomasahle   File: tune.py    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 12
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    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 13
Project: WebPocket   Author: TuuuNya   File: argparse_completer.py    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 14
Project: termfunk   Author: smetj   File: helpformatter.py    GNU General Public License v3.0 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)s"
        return help 
Example 15
Project: aiven-client   Author: aiven   File: argx.py    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 16
Project: osparc-simcore   Author: ITISFoundation   File: cli.py    MIT License 5 votes vote down vote up
def setup_parser(parser):
    """ Adds all options to a parser"""
    #parser.add_argument('names', metavar='NAME', nargs=argparse.ZERO_OR_MORE,
    #                help="A name of something.")

    add_cli_options(parser, CLI_DEFAULT_CONFIGFILE)

    # Add here more options ....

    return parser 
Example 17
Project: csaf-parser   Author: oasis-open   File: cvrf_util.py    MIT License 5 votes vote down vote up
def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs == argparse.ZERO_OR_MORE:
            result = "[%s ...]" % get_metavar(1)
        elif action.nargs == argparse.ONE_OR_MORE:
            result = "%s [...]" % get_metavar(1)
        else:
            result = super(NonDupBracketFormatter, self)._format_args(
                action, default_metavar)
        return result


# is node in the vuln namespace? 
Example 18
Project: aquests   Author: hansroh   File: cli.py    MIT License 5 votes vote down vote up
def make_positional_argument(parser):
    parser.add_argument(
        'method', metavar='METHOD', nargs=OPTIONAL, default='GET',
        help=dedent("""
        The HTTP method to be used for the request
        (GET, POST, PUT, DELETE, ...).
        """))
    parser.add_argument(
        '_url', metavar='URL',
        help=dedent("""
        The scheme defaults to 'https://' if the URL does not include one.
        """))
    parser.add_argument(
        'items',
        metavar='REQUEST_ITEM',
        nargs=ZERO_OR_MORE,
        type=KeyValueArgType(*SEP_GROUP_ITEMS),
        help=dedent("""
        Optional key-value pairs to be included in the request.
        The separator used determines the type:

        ':' HTTP headers:

            Referer:http://httpie.org  Cookie:foo=bar  User-Agent:bacon/1.0

        '==' URL parameters to be appended to the request URI:

            search==hyper

        '=' Data fields to be serialized into a JSON object:

            name=Hyper  language=Python  description='CLI HTTP client'
        """)) 
Example 19
Project: management-api   Author: rancher   File: my_argparse.py    Apache License 2.0 5 votes vote down vote up
def action_is_open(action):
    ''' Returns True if action could consume more arguments (i.e., its pattern is open).
    '''
    return action.nargs in [ZERO_OR_MORE, ONE_OR_MORE, PARSER, REMAINDER] 
Example 20
Project: management-api   Author: rancher   File: my_argparse.py    Apache License 2.0 5 votes vote down vote up
def action_is_open(action):
    ''' Returns True if action could consume more arguments (i.e., its pattern is open).
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [ZERO_OR_MORE, ONE_OR_MORE, PARSER, REMAINDER]:
        return True
    if action.nargs == OPTIONAL or action.nargs is None:
        return num_consumed_args == 0

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args < action.nargs 
Example 21
Project: management-api   Author: rancher   File: my_argparse.py    Apache License 2.0 5 votes vote down vote up
def action_is_open(action):
    ''' Returns True if action could consume more arguments (i.e., its pattern is open).
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [ZERO_OR_MORE, ONE_OR_MORE, PARSER, REMAINDER]:
        return True
    if action.nargs == OPTIONAL or action.nargs is None:
        return num_consumed_args == 0

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args < action.nargs 
Example 22
Project: cmd2   Author: python-cmd2   File: argparse_completer.py    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 = INFINITY
            elif self.action.nargs == argparse.ONE_OR_MORE:
                self.min = 1
                self.max = INFINITY
            else:
                self.min = self.action.nargs
                self.max = self.action.nargs 
Example 23
Project: pygtftk   Author: dputhier   File: arg_formatter.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_help_string(self, action):
        help_str = 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:
                    if isinstance(action.default, io.IOBase):
                        help_str += ' (default: ' + \
                                    str(action.default.name) + ')'
                    else:
                        help_str += ' (default: %(default)s)'
        return help_str 
Example 24
Project: iiita-updates   Author: mrsaicharan1   File: my_argparse.py    Apache License 2.0 5 votes vote down vote up
def action_is_open(action):
    ''' Returns True if action could consume more arguments (i.e., its pattern is open).
    '''
    num_consumed_args = _num_consumed_args.get(action, 0)

    if action.nargs in [ZERO_OR_MORE, ONE_OR_MORE, PARSER, REMAINDER]:
        return True
    if action.nargs == OPTIONAL or action.nargs is None:
        return num_consumed_args == 0

    assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
    return num_consumed_args < action.nargs 
Example 25
Project: shellish   Author: mayfield   File: completer.py    MIT License 5 votes vote down vote up
def parse_nargs(self, nargs):
        """ Nargs is essentially a multi-type encoding.  We have to parse it
        to understand how many values this action may consume. """
        self.max_args = self.min_args = 0
        if nargs is None:
            self.max_args = self.min_args = 1
        elif nargs == argparse.OPTIONAL:
            self.max_args = 1
        elif nargs == argparse.ZERO_OR_MORE:
            self.max_args = None
        elif nargs in (argparse.ONE_OR_MORE, argparse.REMAINDER):
            self.min_args = 1
            self.max_args = None
        elif nargs != argparse.PARSER:
            self.max_args = self.min_args = nargs 
Example 26
Project: Wild-Find   Author: EarToEarOak   File: utils.py    GNU General Public License v2.0 5 votes vote down vote up
def _get_help_string(self, action):
        help = action.help

        if action.required:
            help += ' (required)'

        if action.default is not None and '%(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