Python argparse 模块,OPTIONAL 实例源码

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

项目: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
项目: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
项目:teras    作者:chantera    | 项目源码 | 文件源码
def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None):
        if nargs == 0:
            raise ValueError('nargs for append actions must be > 0')
        if const is not None and nargs != argparse.OPTIONAL:
            raise ValueError('nargs must be %r to supply const'
                             % argparse.OPTIONAL)
        super(_StoreDictAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            const=const,
            default=default,
            type=type,
            choices=choices,
            required=required,
            help=help,
            metavar=metavar)
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
def parse_qubes_app(self, parser, namespace):
        assert hasattr(namespace, 'app')
        setattr(namespace, 'domains', [])
        app = namespace.app
        if hasattr(namespace, 'all_domains') and namespace.all_domains:
            namespace.domains = [
                vm
                for vm in app.domains
                if not vm.klass == 'AdminVM' and
                   vm.name not in namespace.exclude
            ]
        else:
            if hasattr(namespace, 'exclude') and namespace.exclude:
                parser.error('--exclude can only be used with --all')

            if self.nargs == argparse.OPTIONAL:
                vm_name = getattr(namespace, self.dest, None)
                if vm_name is not None:
                    try:
                        namespace.domains += [app.domains[vm_name]]
                    except KeyError:
                        parser.error('no such domain: {!r}'.format(vm_name))
            else:
                for vm_name in getattr(namespace, self.dest):
                    try:
                        namespace.domains += [app.domains[vm_name]]
                    except KeyError:
                        parser.error('no such domain: {!r}'.format(vm_name))
项目:porcupine    作者:Akuli    | 项目源码 | 文件源码
def __init__(self, option_strings, dest, nargs=None, const=None,
                 default=None, type=None, choices=None, required=False,
                 help=None, metavar=None):
        assert nargs != 0 and (const is None or nargs == argparse.OPTIONAL)
        super().__init__(option_strings=option_strings, dest=dest, nargs=nargs,
                         const=const, default=default, type=type,
                         choices=choices, required=required, help=help,
                         metavar=metavar)
项目: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'
        """))
项目:HashDigestBot    作者:wagnerluis1982    | 项目源码 | 文件源码
def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None,
                 required=False, help=None, metavar=None):
        if not option_strings:
            raise ValueError('at least one option argument must be supplied')
        if nargs == 0:
            raise ValueError('nargs for option-values actions must be > 0')
        if const is not None and nargs != argparse.OPTIONAL:
            raise ValueError('nargs must be %r to supply const' % argparse.OPTIONAL)
        super().__init__(option_strings, dest, nargs, const, default, type, choices, required, help, metavar)
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
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()