Python argparse.ONE_OR_MORE Examples

The following are 15 code examples for showing how to use argparse.ONE_OR_MORE(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    License: 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 2
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    License: 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 3
Project: cmd2   Author: python-cmd2   File: argparse_custom.py    License: 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 4
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    License: 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-client   Author: QubesOS   File: __init__.py    License: 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: openaps-predict   Author: loudnate   File: __init__.py    License: MIT License 6 votes vote down vote up
def configure_app(app, parser):
        parser.add_argument(
            'effects',
            nargs=argparse.ONE_OR_MORE,
            help='JSON-encoded effect schedules data files'
        )

        parser.add_argument(
            '--glucose',
            help='JSON-encoded glucose data file in reverse-chronological order'
        )

        parser.add_argument(
            '--momentum',
            help='JSON-encoded momentum effect schedule data file'
        ) 
Example 7
Project: streamlink   Author: streamlink   File: argparser.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _match_argument(self, action, arg_strings_pattern):
        # - https://github.com/streamlink/streamlink/issues/971
        # - https://bugs.python.org/issue9334

        # match the pattern for this action to the arg strings
        nargs_pattern = self._get_nargs_pattern(action)
        match = argparse._re.match(nargs_pattern, arg_strings_pattern)

        # if no match, see if we can emulate optparse and return the
        # required number of arguments regardless of their values
        if match is None:
            nargs = action.nargs if action.nargs is not None else 1
            if isinstance(nargs, numbers.Number) and len(arg_strings_pattern) >= nargs:
                return nargs

        # raise an exception if we weren't able to find a match
        if match is None:
            nargs_errors = {
                None: argparse._('expected one argument'),
                argparse.OPTIONAL: argparse._('expected at most one argument'),
                argparse.ONE_OR_MORE: argparse._('expected at least one argument'),
            }
            default = argparse.ngettext('expected %s argument',
                                        'expected %s arguments',
                                        action.nargs) % action.nargs
            msg = nargs_errors.get(action.nargs, default)
            raise argparse.ArgumentError(action, msg)

        # return the number of arguments matched
        return len(match.group(1)) 
Example 8
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    License: 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 9
Project: WebPocket   Author: TuuuNya   File: argparse_completer.py    License: 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 10
Project: cmd2   Author: python-cmd2   File: test_argparse_custom.py    License: MIT License 5 votes vote down vote up
def test_apcustom_narg_tuple_one_base():
    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(1,))
    assert arg.nargs == argparse.ONE_OR_MORE
    assert arg.nargs_range is None
    assert "arg [...]" in parser.format_help()

    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(1, 5))
    assert arg.nargs == argparse.ONE_OR_MORE
    assert arg.nargs_range == (1, 5)
    assert "arg{1..5}" in parser.format_help()


# noinspection PyUnresolvedReferences 
Example 11
Project: cmd2   Author: python-cmd2   File: test_argparse_custom.py    License: MIT License 5 votes vote down vote up
def test_apcustom_narg_tuple_other_ranges():

    # Test range with no upper bound on max
    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(2,))
    assert arg.nargs == argparse.ONE_OR_MORE
    assert arg.nargs_range == (2, constants.INFINITY)

    # Test finite range
    parser = Cmd2ArgumentParser()
    arg = parser.add_argument('arg', nargs=(2, 5))
    assert arg.nargs == argparse.ONE_OR_MORE
    assert arg.nargs_range == (2, 5) 
Example 12
Project: cmd2   Author: python-cmd2   File: argparse_completer.py    License: 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 13
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    License: 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 14
Project: ceph-lcm   Author: Mirantis   File: cliutils.py    License: Apache License 2.0 5 votes vote down vote up
def mongolock_cli():
    @configure
    def main():
        parser = argparse.ArgumentParser(
            description="Run program, acquiring the lock in MongoDB"
        )
        parser.add_argument(
            "-l", "--lockname",
            help="Name of the lock",
            required=True
        )
        parser.add_argument(
            "-b", "--block",
            help="Block execution till lock will be available",
            action="store_true",
            default=False
        )
        parser.add_argument(
            "-t", "--timeout",
            help="Timeout for blocking",
            type=int,
            default=None
        )
        parser.add_argument(
            "command",
            help="Command to run",
            nargs=argparse.ONE_OR_MORE,
        )
        options = parser.parse_args()

        locked = lock.with_autoprolong_lock(
            options.lockname,
            block=options.block, timeout=options.timeout)

        with locked:
            pty.spawn(options.command)

    return main() 
Example 15
Project: ceph-lcm   Author: Mirantis   File: ceph_verify.py    License: Apache License 2.0 4 votes vote down vote up
def get_options():
    parser = argparse.ArgumentParser(description="Verificator of Ceph version")

    parser.add_argument(
        "-t", "--type",
        default="deb",
        help="Type of the repository. Default is 'deb'."
    )
    parser.add_argument(
        "-c", "--orig-comps",
        default=["main"],
        nargs=argparse.ONE_OR_MORE,
        help="Repository names. 'main' is the default one."
    )
    parser.add_argument(
        "-u", "--repo-url",
        help="URL of the repository"
    )
    parser.add_argument(
        "-d", "--distro-source",
        default="",
        help="release of the repository."
    )
    parser.add_argument(
        "-p", "--package-name",
        default="ceph-common",
        help="package name to verify."
    )
    parser.add_argument(
        "--no-verify-packages",
        action="store_true",
        default=False,
        help="skip package version verification."
    )
    parser.add_argument(
        "--no-verify-installed-versions",
        action="store_true",
        default=False,
        help="skip installed version verification."
    )
    parser.add_argument(
        "--no-verify-repo-candidate",
        action="store_true",
        default=False,
        help="skip verification of remote APT repo."
    )

    parser.add_argument(
        "directory",
        help="directory with fetched files."
    )
    parser.add_argument(
        "raw_deb_url",
        nargs=argparse.OPTIONAL,
        help="raw repo string to use. If set, then -u, -c, -d and -t "
             "are ignored."
    )

    return parser.parse_args()