Python argparse.ZERO_OR_MORE() Examples

The following are code examples for showing how to use argparse.ZERO_OR_MORE(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: argparseinator   Author: ellethee   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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 
Example 2
Project: cheribuild   Author: CTSRD-CHERI   File: loader.py    (license) View Source Project 6 votes vote down vote up
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
            ) 
Example 3
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 4
Project: ceph-lcm   Author: Mirantis   File: cliutils.py    (license) View Source Project 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 5
Project: chat-roulette-python   Author: ph4r05   File: unzip.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 6
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    (license) View Source Project 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 7
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    (license) View Source Project 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 8
Project: TCP-IP   Author: JackZ0   File: cli.py    (license) View Source Project 5 votes vote down vote up
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" 
Example 9
Project: Intranet-Penetration   Author: yuxiaokui   File: cli.py    (license) View Source Project 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 10
Project: MKFQ   Author: maojingios   File: cli.py    (license) View Source Project 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 11
Project: xxNet   Author: drzorm   File: cli.py    (license) View Source Project 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 12
Project: skaff   Author: jhxie   File: clitools.py    (license) View Source Project 5 votes vote down vote up
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 
Example 13
Project: cligraphy   Author: Netflix-Skunkworks   File: parsers.py    (license) View Source Project 5 votes vote down vote up
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 
Example 14
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    (license) View Source Project 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__(**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) 
Example 15
Project: Docker-XX-Net   Author: kuanghy   File: cli.py    (license) View Source Project 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 16
Project: chat-roulette-python   Author: ph4r05   File: main.py    (license) View Source Project 4 votes vote down vote up
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)