Python argparse 模块,ZERO_OR_MORE 实例源码

我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用argparse.ZERO_OR_MORE

项目:argparseinator    作者:ellethee    | 项目源码 | 文件源码
def formatter_factory(show_defaults=True):
    """Formatter factory"""
    def get_help_string(self, action):
        lhelp = action.help
        if isinstance(show_defaults, (list, tuple)):
            if "-" + action.dest in show_defaults:
                return lhelp
        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:
                    lhelp += ' (default: %(default)s)'
        return lhelp

    def default_help_string(self, action):
        return action.help
    if show_defaults is True:
        ARPIFormatter._get_help_string = classmethod(get_help_string)
    else:
        ARPIFormatter._get_help_string = classmethod(default_help_string)
    return ARPIFormatter
项目:cheribuild    作者:CTSRD-CHERI    | 项目源码 | 文件源码
def finalizeOptions(self, availableTargets: list):
        targetOption = self._parser.add_argument("targets", metavar="TARGET", nargs=argparse.ZERO_OR_MORE,
                                                 help="The targets to build", choices=availableTargets + [[]])
        if argcomplete and "_ARGCOMPLETE" in os.environ:
            # if IS_FREEBSD: # FIXME: for some reason this won't work
            excludes = ["-t", "--skip-dependencies"]
            if sys.platform.startswith("freebsd"):
                excludes += ["--freebsd-builder-copy-only", "--freebsd-builder-hostname",
                             "--freebsd-builder-output-path"]

            visibleTargets = availableTargets.copy()
            visibleTargets.remove("__run_everything__")
            targetCompleter = argcomplete.completers.ChoicesCompleter(visibleTargets)
            targetOption.completer = targetCompleter
            # make sure we get target completion for the unparsed args too by adding another zero_or more options
            # not sure why this works but it's a nice hack
            unparsed = self._parser.add_argument("targets", metavar="TARGET", type=list, nargs=argparse.ZERO_OR_MORE,
                                                 help=argparse.SUPPRESS, choices=availableTargets)
            unparsed.completer = targetCompleter
            argcomplete.autocomplete(
                self._parser,
                always_complete_options=None,  # don't print -/-- by default
                exclude=excludes,  # hide these options from the output
                print_suppressed=True,  # also include target-specific options
            )
项目:CSB    作者:csb-toolbox    | 项目源码 | 文件源码
def add_array_option(self, name, shortname, type, help, default=None, choices=None, required=False):
        """
        Define an array option (a dashed argument that may receive one
        or multiple values on the command line, separated with spaces).

        @param name: long name of the option (or None)
        @type name: str, None
        @param shortname: short (single character) name of the option (or None)
        @type shortname: str, None
        @param type: argument data type
        @type type: type (type factory callable)        
        @param help: help text
        @type help: str
        @param choices: list of allowed argument values
        @type choices: tuple
        @param required: make this option a named mandatory argument
        @type required: bool                   
        """
        help = self._format_help(help, default)      

        self._add(ArgHandler.Type.NAMED, name, shortname,
                  nargs=argparse.ZERO_OR_MORE, type=type, help=help, default=default,
                  choices=choices, required=required)
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
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()
项目:chat-roulette-python    作者:ph4r05    | 项目源码 | 文件源码
def app_main(self):
        parser = argparse.ArgumentParser(description='Unzip all archives in the directory')

        parser.add_argument('--dir', dest='dir', default='unpack',
                            help='default directory for unpacking')

        parser.add_argument('zipdir', nargs=argparse.ZERO_OR_MORE, default=[],
                            help='directories with ZIP files to unpack')

        self.args = parser.parse_args()
        self.resdir = self.args.dir
        self.srcdir = self.args.zipdir[0]

        # analyze source dir
        for (dirpath, dirnames, filenames) in walk(self.srcdir):
            for filename in filenames:
                if not filename.lower().endswith('.zip'):
                    continue
                self.zips.append(os.path.join(dirpath, filename))
            break

        self.unzip()
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
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)
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
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)
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def _get_help_string(self, action):
        helpstr = action.help
        if '%(default)' not in action.help and '(default:' not in action.help:
            if action.default != argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    helpstr += ' (default: %(default)s)'
        return helpstr

# The attributes here are:
# short: a string that will be displayed by "certbot -h commands"
# opts:  a string that heads the section of flags with which this command is documented,
#        both for "certbot -h SUBCOMMAND" and "certbot -h all"
# usage: an optional string that overrides the header of "certbot -h SUBCOMMAND"
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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'
        """))
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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'
        """))
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
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'
        """))
项目:skaff    作者:jhxie    | 项目源码 | 文件源码
def _get_help_string(self, action):
        if self._add_defaults is None:
            return argparse.HelpFormatter._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)'
        return help
项目:cligraphy    作者:Netflix-Skunkworks    | 项目源码 | 文件源码
def _get_help_string(self, action):
        help = action.help
        if '(default' not in help and type(action) not in (argparse._StoreConstAction, argparse._StoreTrueAction, argparse._StoreFalseAction):
            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
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
def __init__(self, want_app=True, want_app_no_instance=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._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)

        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)
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
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'
        """))
项目:chat-roulette-python    作者:ph4r05    | 项目源码 | 文件源码
def app_main(self):
        # Backup original arguments for later parsing
        args_src = sys.argv

        # Parse our argument list
        parser = argparse.ArgumentParser(description='Chat roulette python server')
        parser.add_argument('-n', '--non-interactive', dest='noninteractive', action='store_const', const=True,
                            help='non-interactive mode of operation, command line only')
        parser.add_argument('-r', '--attempts', dest='attempts', type=int, default=3,
                            help='number of attempts in non-interactive mode')
        parser.add_argument('-l','--pid-lock', dest='pidlock', type=int, default=-1,
                            help='number of attempts for pidlock acquire')
        parser.add_argument('--debug', dest='debug', action='store_const', const=True,
                            help='enables debug mode')
        parser.add_argument('--verbose', dest='verbose', action='store_const', const=True,
                            help='enables verbose mode')
        parser.add_argument('--force', dest='force', action='store_const', const=True, default=False,
                            help='forces some action')

        parser.add_argument('commands', nargs=argparse.ZERO_OR_MORE, default=[],
                            help='commands to process')

        self.args = parser.parse_args(args=args_src[1:])
        self.noninteractive = self.args.noninteractive

        # Fixing cmd2 arg parsing, call cmdLoop
        sys.argv = [args_src[0]]
        for cmd in self.args.commands:
            sys.argv.append(cmd)

        # Terminate after execution is over on the non-interactive mode
        if self.noninteractive:
            sys.argv.append('quit')

        if self.args.debug:
            coloredlogs.install(level=logging.DEBUG)

        self.cmdloop()
        sys.argv = args_src

        # Noninteractive - return the last result from the operation (for scripts)
        if self.noninteractive:
            sys.exit(self.last_result)