Python argparse.OPTIONAL Examples
The following are 27
code examples of argparse.OPTIONAL().
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 also want to check out all available functions/classes of the module
argparse
, or try the search function
.
Example #1
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
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
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
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
Source File: custom_help_formatter.py From GTDBTk with GNU General Public License v3.0 | 6 votes |
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 \ not isinstance(type(action.default), bool): 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 #4
Source File: custom_help_formatter.py From SqueezeMeta with GNU General Public License v3.0 | 6 votes |
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) != bool: 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 #5
Source File: __init__.py From openaps-predict with MIT License | 6 votes |
def configure_app(app, parser): parser.add_argument( 'history', help='JSON-encoded pump history data file, normalized by openapscontrib.mmhistorytools' ) parser.add_argument( '--absorption-time', type=int, nargs=argparse.OPTIONAL, help='The total length of carbohydrate absorption in minutes' ) parser.add_argument( '--absorption-delay', type=int, nargs=argparse.OPTIONAL, help='The delay time between a dosing event and when absorption begins' )
Example #6
Source File: test_argparse_custom.py From cmd2 with MIT License | 6 votes |
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 #7
Source File: __init__.py From openaps-predict with MIT License | 6 votes |
def configure_app(app, parser): parser.add_argument( 'glucose', help='JSON-encoded glucose data file in reverse-chronological order' ) parser.add_argument( '--prediction-time', type=int, nargs=argparse.OPTIONAL, help='The total length of forward trend extrapolation in minutes. Defaults to 30.' ) parser.add_argument( '--calibrations', nargs=argparse.OPTIONAL, help='JSON-encoded sensor calibrations data file in reverse-chronological order' )
Example #8
Source File: __init__.py From qubes-core-admin-client with GNU Lesser General Public License v2.1 | 6 votes |
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 #9
Source File: __init__.py From qubes-core-admin-client with GNU Lesser General Public License v2.1 | 6 votes |
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 #10
Source File: argparser.py From streamlink with BSD 2-Clause "Simplified" License | 5 votes |
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 #11
Source File: customHelpFormatter.py From SqueezeMeta with GNU General Public License v3.0 | 5 votes |
def _get_help_string(self, action): h = action.help if '%(default)' not in action.help: if action.default != '' and action.default != [] and action.default != None and action.default != False: 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 #12
Source File: __init__.py From openaps-predict with MIT License | 5 votes |
def configure_app(app, parser): parser.add_argument( 'history', help='JSON-encoded pump history data file, normalized by openapscontrib.mmhistorytools' ) parser.add_argument( '--settings', nargs=argparse.OPTIONAL, help='JSON-encoded pump settings file, optional if --insulin-action-curve is set' ) parser.add_argument( '--insulin-action-curve', nargs=argparse.OPTIONAL, type=float, choices=range(3, 7), help='Insulin action curve, optional if --settings is set' ) parser.add_argument( '--insulin-sensitivities', help='JSON-encoded insulin sensitivities schedule file' ) parser.add_argument( '--basal-dosing-end', nargs=argparse.OPTIONAL, help='The timestamp at which temp basal dosing should be assumed to end, ' 'as a JSON-encoded pump clock file' ) parser.add_argument( '--absorption-delay', type=int, nargs=argparse.OPTIONAL, help='The delay time between a dosing event and when absorption begins' )
Example #13
Source File: __init__.py From openaps-predict with MIT License | 5 votes |
def configure_app(app, parser): parser.add_argument( 'history', help='JSON-encoded pump history data file, normalized by openapscontrib.mmhistorytools' ) parser.add_argument( '--carb-ratios', help='JSON-encoded carb ratio schedule file' ) parser.add_argument( '--insulin-sensitivities', help='JSON-encoded insulin sensitivities schedule file' ) parser.add_argument( '--absorption-time', type=int, nargs=argparse.OPTIONAL, help='The total length of carbohydrate absorption in minutes' ) parser.add_argument( '--absorption-delay', type=int, nargs=argparse.OPTIONAL, help='The delay time between a dosing event and when absorption begins' )
Example #14
Source File: optparse.py From pycbc with GNU General Public License v3.0 | 5 votes |
def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): if type is not None: self.internal_type=type else: self.internal_type=str new_default = DictWithDefaultReturn(lambda: default) #new_default.default_value=default if nargs == 0: raise ValueError('nargs for append actions must be > 0; if arg ' 'strings are not supplying the value to append, ' 'the append const action may be more appropriate') if const is not None and nargs != argparse.OPTIONAL: raise ValueError('nargs must be %r to supply const' % argparse.OPTIONAL) super(MultiDetOptionAction, self).__init__( option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=new_default, type=str, choices=choices, required=required, help=help, metavar=metavar)
Example #15
Source File: pipelineWrapper.py From protect with Apache License 2.0 | 5 votes |
def _get_help_string(self, action): ''' This module was taken from the RawDescriptionHelpFormatter class within argparse. It deals with the formatting of the description string and allows properly formatted descriptions ot be printed without line wrapping. ''' 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 #16
Source File: qvm_volume.py From qubes-core-admin-client with GNU Lesser General Public License v2.1 | 5 votes |
def init_info_parser(sub_parsers): ''' Add 'info' action related options ''' info_parser = sub_parsers.add_parser( 'info', aliases=('i',), help='info about volume') info_parser.add_argument(metavar='VM:VOLUME', dest='volume', action=qubesadmin.tools.VMVolumeAction) info_parser.add_argument(dest='property', action='store', nargs=argparse.OPTIONAL, help='Show only this property instead of all of them; use ' '\'revisions\' to list available revisions') info_parser.set_defaults(func=info_volume)
Example #17
Source File: __init__.py From qubes-core-admin-client with GNU Lesser General Public License v2.1 | 5 votes |
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 #18
Source File: __init__.py From qubes-core-admin-client with GNU Lesser General Public License v2.1 | 5 votes |
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))
Example #19
Source File: argument_parsing.py From ClusterRunner with Apache License 2.0 | 5 votes |
def _get_help_string(self, action): """ Appends the default argument value to the help string for non-required args that have default values. This implementation is loosely based off of the argparse.ArgumentDefaultsHelpFormatter. """ help_string = action.help if not action.required: if action.default not in (argparse.SUPPRESS, None): defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE] if action.option_strings or action.nargs in defaulting_nargs: # using old string formatting style here because argparse internals use that help_string += ' (default: %(default)s)' return help_string
Example #20
Source File: argparse_completer.py From cmd2 with MIT License | 5 votes |
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 #21
Source File: CLI.py From ColorWallpaper with GNU General Public License v3.0 | 5 votes |
def _get_help_string(self, action): self.default = None if action.default not in (None, argparse.SUPPRESS): if action.option_strings or action.nargs in (argparse.OPTIONAL, argparse.ZERO_OR_MORE): self.default = self.__format_map.get(action.dest, lambda s: s)(action.default) return action.help
Example #22
Source File: argx.py From aiven-client with Apache License 2.0 | 5 votes |
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 #23
Source File: params.py From ParlAI with MIT License | 5 votes |
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: %(default)s)' if ( hasattr(action, 'recommended') and action.recommended and action.recommended != action.default ): help += '(recommended: %(recommended)s)' help = help.replace(')(recommended', ', recommended') return help
Example #24
Source File: tune.py From fastchess with GNU General Public License v3.0 | 5 votes |
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 #25
Source File: args.py From review with Mozilla Public License 2.0 | 4 votes |
def parse_args(argv): main_parser = argparse.ArgumentParser(add_help=False) main_parser.add_argument("--version", action="store_true", help=argparse.SUPPRESS) main_parser.add_argument( "--trace", "--debug", action="store_true", help=argparse.SUPPRESS ) parser = argparse.ArgumentParser(parents=[main_parser]) commands_parser = parser.add_subparsers( dest="command", metavar="COMMAND", description="For full command description: moz-phab COMMAND -h", ) commands_parser.required = True for command in commands.__all__: module = import_module("mozphab.commands.{}".format(command)) add_parser = getattr(module, "add_parser", None) if callable(add_parser): add_parser(commands_parser) logger.debug("Command added - %s", command) help_parser = commands_parser.add_parser("help") help_parser.add_argument("command", nargs=argparse.OPTIONAL) help_parser.set_defaults(print_help=True) # if we're called without a command and from within a repository, # default to submit. if not argv or ( not (set(argv) & {"-h", "--help"}) and argv[0] not in [choice for choice in commands_parser.choices] and find_repo_root(os.getcwd()) ): logger.debug("defaulting to `submit`") argv.insert(0, "submit") main_args, unknown = main_parser.parse_known_args(argv) # map --version to the 'version' command if main_args.version: unknown = ["version"] args = parser.parse_args(unknown) # copy across parsed main_args; they are defined in `args`, but not set for name, value in vars(main_args).items(): args.__setattr__(name, value) # handle the help command here as printing help needs access to the parser if hasattr(args, "print_help"): help_argv = ["--help"] if args.command: help_argv.insert(0, args.command) # parse_args calls parser.exit() when passed --help parser.parse_args(help_argv) return args
Example #26
Source File: __init__.py From openaps-predict with MIT License | 4 votes |
def configure_app(app, parser): parser.add_argument( 'history', help='JSON-encoded pump history data file, normalized by openapscontrib.mmhistorytools' ) parser.add_argument( '--settings', nargs=argparse.OPTIONAL, help='JSON-encoded pump settings file, optional if --insulin-action-curve is set' ) parser.add_argument( '--insulin-action-curve', nargs=argparse.OPTIONAL, type=float, choices=range(3, 7), help='Insulin action curve, optional if --settings is set' ) parser.add_argument( '--basal-dosing-end', nargs=argparse.OPTIONAL, help='The timestamp at which temp basal dosing should be assumed to end, ' 'as a JSON-encoded pump clock file' ) parser.add_argument( '--absorption-delay', type=int, nargs=argparse.OPTIONAL, help='The delay time between a dosing event and when absorption begins' ) parser.add_argument( '--start-at', nargs=argparse.OPTIONAL, help='File containing the timestamp at which to truncate the beginning of the output, ' 'as a JSON-encoded ISO date' ) parser.add_argument( '--end-at', nargs=argparse.OPTIONAL, help='File containing the timestamp at which to truncate the end of the output, ' 'as a JSON-encoded ISO date' )
Example #27
Source File: ceph_verify.py From ceph-lcm with Apache License 2.0 | 4 votes |
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()