Python argparse.html() Examples
The following are 30
code examples of argparse.html().
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: argument_parsing.py From ClusterRunner with Apache License 2.0 | 7 votes |
def _get_option_tuples(self, option_string): """ This method is overridden explicitly to disable argparse prefix matching. Prefix matching is an undesired default behavior as it creates the potential for unintended breaking changes just by adding a new command-line argument. For example, if a user uses the argument "--master" to specify a value for "--master-url", and later we add a new argument named "--master-port", that change will break the user script that used "--master". See: https://docs.python.org/3.4/library/argparse.html#argument-abbreviations-prefix-matching """ # This if statement comes from the superclass implementation -- it precludes a code path in the superclass # that is responsible for checking for argument prefixes. The return value of an empty list is the way that # this method communicates no valid arguments were found. chars = self.prefix_chars if option_string[0] in chars and option_string[1] in chars: return [] return super()._get_option_tuples(option_string)
Example #2
Source File: ui.py From python-wifi-survey-heatmap with GNU Affero General Public License v3.0 | 6 votes |
def parse_args(argv): """ parse arguments/options this uses the new argparse module instead of optparse see: <https://docs.python.org/2/library/argparse.html> """ p = argparse.ArgumentParser(description='wifi survey data collection UI') p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output. specify twice for debug-level output.') p.add_argument('INTERFACE', type=str, help='Wireless interface name') p.add_argument('SERVER', type=str, help='iperf3 server IP or hostname') p.add_argument('IMAGE', type=str, help='Path to background image') p.add_argument( 'TITLE', type=str, help='Title for survey (and data filename)' ) args = p.parse_args(argv) return args
Example #3
Source File: common.py From surreal with MIT License | 6 votes |
def add(self, *args, **kwargs): default = kwargs.get('default') dtype = kwargs.get('type') if dtype is None: if default is None: dtype = str else: dtype = type(default) typename = dtype.__name__ if 'metavar' not in kwargs: # metavar: display --foo <float=0.05> in help string if 'choices' in kwargs: choices = kwargs['choices'] choices_str = '/'.join(['{}']*len(choices)).format(*choices) kwargs['metavar'] = '<{}: {}>'.format(typename, choices_str) elif 'nargs' in kwargs: # better formatting handled in _SingleMetavarFormatter kwargs['metavar'] = '{}'.format(typename) elif not kwargs.get('action'): # if 'store_true', then no metavar needed # list of actions: https://docs.python.org/3/library/argparse.html#action default_str = '={}'.format(default) if default else '' kwargs['metavar'] = '<{}{}>'.format(typename, default_str) self.parser.add_argument(*args, **kwargs)
Example #4
Source File: endpointscfg.py From python-compat-runtime with Apache License 2.0 | 6 votes |
def error(self, message): """Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentation for detailed method information: http://docs.python.org/2/library/argparse.html#exiting-methods Args: message: original error message that will be printed to stderr """ subcommands_quoted = ', '.join( [repr(command) for command in _VISIBLE_COMMANDS]) subcommands = ', '.join(_VISIBLE_COMMANDS) message = re.sub( r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$' % subcommands, r'\1 (choose from %s)' % subcommands_quoted, message) super(_EndpointsParser, self).error(message)
Example #5
Source File: argparse_flags.py From abseil-py with Apache License 2.0 | 6 votes |
def __call__(self, parser, namespace, values, option_string=None): """See https://docs.python.org/3/library/argparse.html#action-classes.""" # This only prints flags when help is not argparse.SUPPRESS. # It includes user defined argparse flags, as well as main module's # key absl flags. Other absl flags use argparse.SUPPRESS, so they aren't # printed here. parser.print_help() absl_flags = parser._inherited_absl_flags # pylint: disable=protected-access if absl_flags: modules = sorted(absl_flags.flags_by_module_dict()) main_module = sys.argv[0] if main_module in modules: # The main module flags are already printed in parser.print_help(). modules.remove(main_module) print(absl_flags._get_help_for_modules( # pylint: disable=protected-access modules, prefix='', include_special_flags=True)) parser.exit()
Example #6
Source File: run_RG2Sp_estim_shape-models.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def arg_parse_params(): """ SEE: https://docs.python.org/3/library/argparse.html :return {str: str}: """ parser = argparse.ArgumentParser() parser.add_argument('-annot', '--path_annot', type=str, required=False, help='path to directory & name pattern for annotations', default=PATH_ANNOT) parser.add_argument('-out', '--path_out', type=str, required=False, help='path to the output directory', default=PATH_DATA) parser.add_argument('-nb', '--nb_comp', type=int, required=False, help='number of component in Mixture model', default=2) params = vars(parser.parse_args()) for k in (k for k in params if 'path' in k): params[k] = tl_data.update_path(params[k], absolute=True) p = os.path.dirname(params[k]) if k == 'path_annot' else params[k] assert os.path.exists(p), 'missing: %s' % p # load saved configuration logging.info('ARG PARAMETERS: \n %r', params) return params
Example #7
Source File: gui_annot_center_correction.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 6 votes |
def arg_parse_params(): """ SEE: https://docs.python.org/3/library/argparse.html :return dict: """ parser = argparse.ArgumentParser() parser.add_argument('-imgs', '--path_images', type=str, required=False, help='path to dir and image pattern', default=PATH_IMAGES) parser.add_argument('-csv', '--path_csv', type=str, required=False, help='path to the CSV directory', default=PATH_CSV) parser.add_argument('-info', '--path_info', type=str, required=False, help='path to file with complete info', default=None) params = vars(parser.parse_args()) for k in (k for k in params if 'path' in k): if not params[k]: continue params[k] = os.path.abspath(os.path.expanduser(params[k])) p = os.path.dirname(params[k]) if '*' in params[k] else params[k] assert os.path.exists(p), 'missing: %s' % p logging.info('ARG PARAMETERS: \n %r', params) return params
Example #8
Source File: __main__.py From nRF5-universal-prog with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _add_commands(self): """ Split up the functionality of nrfjprog into multiple sub-commands. :param Object subparsers: https://docs.python.org/3/library/argparse.html#sub-commands. """ self._add_erase_command() self._add_halt_command() self._add_ids_command() self._add_memrd_command() self._add_memwr_command() self._add_pinresetenable_command() self._add_program_command() self._add_readback_command() self._add_readregs_command() self._add_readtofile_command() self._add_recover_command() self._add_reset_command() self._add_run_command() self._add_verify_command() self._add_version_command() # The top-level positional commands of our command-line interface.
Example #9
Source File: experiments.py From BIRL with BSD 3-Clause "New" or "Revised" License | 6 votes |
def parse_arg_params(parser, upper_dirs=None): """ parse all params :param parser: object of parser :param list(str) upper_dirs: list of keys in parameters with item for which only the parent folder must exist :return dict: parameters """ # SEE: https://docs.python.org/3/library/argparse.html args = vars(parser.parse_args()) logging.info('ARGUMENTS: \n %r', args) # remove all None parameters args = {k: args[k] for k in args if args[k] is not None} # extend and test all paths in params args, missing = update_paths(args, upper_dirs=upper_dirs) assert not missing, 'missing paths: %r' % {k: args[k] for k in missing} return args
Example #10
Source File: rescale_tissue_landmarks.py From BIRL with BSD 3-Clause "New" or "Revised" License | 6 votes |
def arg_parse_params(): """ argument parser from cmd :return dict: """ # SEE: https://docs.python.org/3/library/argparse.html parser = argparse.ArgumentParser() parser.add_argument('-a', '--path_annots', type=str, required=False, help='path to folder with annotations') parser.add_argument('-d', '--path_dataset', type=str, required=False, help='path to the output directory - dataset') parser.add_argument('--scales', type=int, required=False, nargs='*', help='generated scales for the dataset', default=DEFAULT_SCALES) parser.add_argument('--nb_selected', type=float, required=False, default=None, help='number ot ration of selected landmarks') parser.add_argument('--nb_total', type=int, required=False, default=None, help='total number of generated landmarks') parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS, help='number of processes in parallel') args = parse_arg_params(parser) if not is_iterable(args['scales']): args['scales'] = [args['scales']] return args
Example #11
Source File: _endpointscfg_impl.py From endpoints-python with Apache License 2.0 | 6 votes |
def error(self, message): """Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentation for detailed method information: http://docs.python.org/2/library/argparse.html#exiting-methods Args: message: original error message that will be printed to stderr """ # subcommands_quoted is the same as subcommands, except each value is # surrounded with double quotes. This is done to match the standard # output of the ArgumentParser, while hiding commands we don't want users # to use, as they are no longer documented and only here for legacy use. subcommands_quoted = ', '.join( [repr(command) for command in _VISIBLE_COMMANDS]) subcommands = ', '.join(_VISIBLE_COMMANDS) message = re.sub( r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$' % subcommands, r'\1 (choose from %s)' % subcommands_quoted, message) super(_EndpointsParser, self).error(message)
Example #12
Source File: heatmap.py From python-wifi-survey-heatmap with GNU Affero General Public License v3.0 | 6 votes |
def parse_args(argv): """ parse arguments/options this uses the new argparse module instead of optparse see: <https://docs.python.org/2/library/argparse.html> """ p = argparse.ArgumentParser(description='wifi survey heatmap generator') p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output. specify twice for debug-level output.') p.add_argument('-i', '--ignore', dest='ignore', action='append', default=[], help='SSIDs to ignore from channel graph') p.add_argument('IMAGE', type=str, help='Path to background image') p.add_argument( 'TITLE', type=str, help='Title for survey (and data filename)' ) args = p.parse_args(argv) return args
Example #13
Source File: test_timings.py From biweeklybudget with GNU Affero General Public License v3.0 | 6 votes |
def parse_args(argv): """ parse arguments/options this uses the new argparse module instead of optparse see: <https://docs.python.org/2/library/argparse.html> """ p = argparse.ArgumentParser(description='Report on test run timings') p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output. specify twice for debug-level output.') c = ['acceptance36', 'acceptance27'] p.add_argument('-j', '--jobtype', dest='jobtype', action='store', type=str, choices=c, default=c[0], help='TOXENV for job') p.add_argument('BUILD_NUM', action='store', type=str, nargs='?', default=None, help='TravisCI X.Y build number to analyze; if not ' 'specified, will use latest acceptance36 build.') args = p.parse_args(argv) return args
Example #14
Source File: argparse_flags.py From abseil-py with Apache License 2.0 | 5 votes |
def __call__(self, parser, namespace, values, option_string=None): """See https://docs.python.org/3/library/argparse.html#action-classes.""" if not isinstance(values, list) or values: raise ValueError('values must be an empty list.') if option_string.startswith('--'): option = option_string[2:] else: option = option_string[1:] if option in self._flag_names: self._flag_instance.parse('true') else: if not option.startswith('no') or option[2:] not in self._flag_names: raise ValueError('invalid option_string: ' + option_string) self._flag_instance.parse('false') self._flag_instance.using_default_value = False
Example #15
Source File: bm_comp_perform.py From BIRL with BSD 3-Clause "New" or "Revised" License | 5 votes |
def arg_parse_params(): """ parse the input parameters :return dict: parameters """ # SEE: https://docs.python.org/3/library/argparse.html parser = argparse.ArgumentParser() parser.add_argument('-o', '--path_out', type=str, required=False, help='path to the output folder', default='') parser.add_argument('-n', '--nb_runs', type=int, required=False, help='number of run experiments', default=5) args = vars(parser.parse_args()) logging.info('ARGUMENTS: \n%r' % args) return args
Example #16
Source File: run_ovary_segm_evaluation.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 5 votes |
def arg_parse_params(paths): """ SEE: https://docs.python.org/3/library/argparse.html :return ({str: ...}, bool, int): """ parser = argparse.ArgumentParser() parser.add_argument('--images', type=str, required=False, help='path to directory & name pattern for images', default=paths['images']) parser.add_argument('--annots', type=str, required=False, help='path to directory & name pattern for annotation', default=paths['annots']) parser.add_argument('--segments', type=str, required=False, help='path to directory & name pattern for segmentation', default=paths['segments']) parser.add_argument('--centers', type=str, required=False, help='path to directory & name pattern for centres', default=paths['centers']) parser.add_argument('--results', type=str, required=False, help='path to the result directory', default=paths['results']) parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS, help='number of processes in parallel') parser.add_argument('--visual', required=False, action='store_true', default=False, help='export visualisations') arg_params = vars(parser.parse_args()) export_visual = arg_params['visual'] for k in (k for k in arg_params if k != 'nb_workers' and k != 'visual'): if not isinstance(arg_params[k], str) or arg_params[k].lower() == 'none': paths[k] = None continue paths[k] = tl_data.update_path(arg_params[k], absolute=True) p = paths[k] if k == 'results' else os.path.dirname(paths[k]) assert os.path.exists(p), 'missing: %s' % p logging.info('ARG PARAMETERS: \n %s', (paths)) return paths, export_visual, arg_params['nb_workers']
Example #17
Source File: run_ellipse_annot_match.py From pyImSegm with BSD 3-Clause "New" or "Revised" License | 5 votes |
def arg_parse_params(params): """ SEE: https://docs.python.org/3/library/argparse.html :return dict: """ parser = argparse.ArgumentParser() parser.add_argument('-imgs', '--path_images', type=str, required=False, help='path to directory & name pattern for images', default=params.get('path_images', None)) parser.add_argument('-ells', '--path_ellipses', type=str, required=False, help='path to directory & name pattern for ellipses', default=params.get('path_ellipses', None)) parser.add_argument('-info', '--path_infofile', type=str, required=False, help='path to the global information file', default=params.get('path_infofile', None)) parser.add_argument('-out', '--path_output', type=str, required=False, help='path to the output directory', default=params.get('path_output', None)) parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS, help='number of processes in parallel') arg_params = vars(parser.parse_args()) params.update(arg_params) for k in (k for k in params if 'path' in k and params[k] is not None): params[k] = tl_data.update_path(params[k], absolute=True) logging.info('ARG PARAMETERS: \n %r', params) return params
Example #18
Source File: argparsing.py From python-netsurv with MIT License | 5 votes |
def addoption(self, *opts, **attrs): """ register a command line option. :opts: option names, can be short or long options. :attrs: same attributes which the ``add_option()`` function of the `argparse library <http://docs.python.org/2/library/argparse.html>`_ accepts. After command line parsing options are available on the pytest config object via ``config.option.NAME`` where ``NAME`` is usually set by passing a ``dest`` attribute, for example ``addoption("--long", dest="NAME", ...)``. """ self._anonymous.addoption(*opts, **attrs)
Example #19
Source File: argparse_flags.py From abseil-py with Apache License 2.0 | 5 votes |
def parse_known_args(self, args=None, namespace=None): if args is None: args = sys.argv[1:] if self._inherited_absl_flags: # Handle --flagfile. # Explicitly specify force_gnu=True, since argparse behaves like # gnu_getopt: flags can be specified after positional arguments. args = self._inherited_absl_flags.read_flags_from_files( args, force_gnu=True) undefok_missing = object() undefok = getattr(namespace, 'undefok', undefok_missing) namespace, args = super(ArgumentParser, self).parse_known_args( args, namespace) # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where # sub-parsers don't preserve existing namespace attributes. # Restore the undefok attribute if a sub-parser dropped it. if undefok is not undefok_missing: namespace.undefok = undefok if self._inherited_absl_flags: # Handle --undefok. At this point, `args` only contains unknown flags, # so it won't strip defined flags that are also specified with --undefok. # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where # sub-parsers don't preserve existing namespace attributes. The undefok # attribute might not exist because a subparser dropped it. if hasattr(namespace, 'undefok'): args = _strip_undefok_args(namespace.undefok, args) # absl flags are not exposed in the Namespace object. See Namespace: # https://docs.python.org/3/library/argparse.html#argparse.Namespace. del namespace.undefok self._inherited_absl_flags.mark_as_parsed() try: self._inherited_absl_flags._assert_all_validators() # pylint: disable=protected-access except flags.IllegalFlagValueError as e: self.error(str(e)) return namespace, args
Example #20
Source File: argparse_flags.py From abseil-py with Apache License 2.0 | 5 votes |
def __call__(self, parser, namespace, values, option_string=None): """See https://docs.python.org/3/library/argparse.html#action-classes.""" self._flag_instance.parse(values) self._flag_instance.using_default_value = False
Example #21
Source File: argparsing.py From python-netsurv with MIT License | 5 votes |
def addoption(self, *opts, **attrs): """ register a command line option. :opts: option names, can be short or long options. :attrs: same attributes which the ``add_option()`` function of the `argparse library <http://docs.python.org/2/library/argparse.html>`_ accepts. After command line parsing options are available on the pytest config object via ``config.option.NAME`` where ``NAME`` is usually set by passing a ``dest`` attribute, for example ``addoption("--long", dest="NAME", ...)``. """ self._anonymous.addoption(*opts, **attrs)
Example #22
Source File: scancli.py From python-wifi-survey-heatmap with GNU Affero General Public License v3.0 | 5 votes |
def parse_args(argv): """ parse arguments/options this uses the new argparse module instead of optparse see: <https://docs.python.org/2/library/argparse.html> """ p = argparse.ArgumentParser(description='wifi scan CLI') p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output. specify twice for debug-level output.') p.add_argument('INTERFACE', type=str, help='Wireless interface name') p.add_argument('SERVER', type=str, help='iperf3 server IP or hostname') args = p.parse_args(argv) return args
Example #23
Source File: cli.py From pypistats with MIT License | 5 votes |
def subcommand(args=None, parent=subparsers): """Decorator to define a new subcommand in a sanity-preserving way. The function will be stored in the ``func`` variable when the parser parses arguments so that it can be called directly like so:: args = cli.parse_args() args.func(args) Usage example:: @subcommand([argument("-d", help="Enable debug mode", action="store_true")]) def subcommand(args): print(args) Then on the command line:: $ python cli.py subcommand -d https://mike.depalatis.net/blog/simplifying-argparse.html """ if args is None: args = [] def decorator(func): func2 = getattr(pypistats, func.__name__) parser = parent.add_parser( func.__name__, description=func2.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) for arg in args: parser.add_argument(*arg[0], **arg[1]) parser.set_defaults(func=func) return decorator
Example #24
Source File: cli.py From cate with MIT License | 5 votes |
def parser_kwargs(cls) -> dict: """ Return parser keyword arguments dictionary passed to a ``argparse.ArgumentParser(**parser_kwargs)`` call. For the possible keywords in the returned dictionary, refer to https://docs.python.org/3.5/library/argparse.html#argparse.ArgumentParser. :return: A keyword arguments dictionary. """
Example #25
Source File: cli.py From cate with MIT License | 5 votes |
def configure_parser(cls, parser: argparse.ArgumentParser) -> None: """ Configure *parser*, i.e. make any required ``parser.add_argument(*args, **kwargs)`` calls. See https://docs.python.org/3.5/library/argparse.html#argparse.ArgumentParser.add_argument :param parser: The command parser to configure. """
Example #26
Source File: cli.py From cate with MIT License | 5 votes |
def execute(self, command_args: argparse.Namespace) -> None: """ Execute this command. The command's arguments in *command_args* are attributes namespace returned by ``argparse.ArgumentParser.parse_args()``. Also refer to to https://docs.python.org/3.5/library/argparse.html#argparse.ArgumentParser.parse_args ``execute``implementations shall raise a ``CommandError`` instance on failure. :param command_args: The command's arguments. """
Example #27
Source File: common.py From surreal with MIT License | 5 votes |
def _get_bound_args(func, *args, **kwargs): """ https://docs.python.org/3/library/inspect.html#inspect.BoundArguments def f(a, b, c=5, d=6): pass get_bound_args(f, 3, 6, d=100) -> {'a':3, 'b':6, 'c':5, 'd':100} Returns: OrderedDict of bound arguments """ arginfo = inspect.signature(func).bind(*args, **kwargs) arginfo.apply_defaults() return arginfo.arguments
Example #28
Source File: avdlDoxyFilter.py From GelReportModels with Apache License 2.0 | 5 votes |
def parse_args(args): """ Takes in the command-line arguments list (args), and returns a nice argparse result with fields for all the options. Borrows heavily from the argparse documentation examples: <http://docs.python.org/library/argparse.html> """ # The command line arguments start with the program name, which we don't # want to treat as an argument for argparse. So we remove it. args = args[1:] # Construct the parser (which is stored in parser) # Module docstring lives in __doc__ # See http://python-forum.com/pythonforum/viewtopic.php?f=3&t=36847 # And a formatter class so our examples in the docstring look good. Isn't it # convenient how we already wrapped it to 80 characters? # See http://docs.python.org/library/argparse.html#formatter-class parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Now add all the options to it parser.add_argument("avdl", type=argparse.FileType('r'), help="the AVDL file to read") return parser.parse_args(args)
Example #29
Source File: __main__.py From nRF5-universal-prog with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): """ Set up a command line interface using the argparse module. Above we will define what arguments our program requires and argparse will figure out how to parse those from sys.argv. For info on argparse see: https://docs.python.org/3/library/argparse.html. """ cli = Nrfjprog() cli.run()
Example #30
Source File: split_images_two_tissues.py From BIRL with BSD 3-Clause "New" or "Revised" License | 5 votes |
def arg_parse_params(): """ parse the input parameters :return dict: parameters """ # SEE: https://docs.python.org/3/library/argparse.html parser = argparse.ArgumentParser() parser.add_argument('--dimension', type=int, required=False, choices=[0, 1], help='cutting dimension', default=CUT_DIMENSION) args = args_expand_parse_images(parser, NB_WORKERS) logging.info('ARGUMENTS: \n%r' % args) return args