当前位置: 首页>>代码示例>>Python>>正文


Python ArgumentParser.parse_args方法代码示例

本文整理汇总了Python中argparse.ArgumentParser.parse_args方法的典型用法代码示例。如果您正苦于以下问题:Python ArgumentParser.parse_args方法的具体用法?Python ArgumentParser.parse_args怎么用?Python ArgumentParser.parse_args使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在argparse.ArgumentParser的用法示例。


在下文中一共展示了ArgumentParser.parse_args方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getArgs

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def getArgs(av):
	r"""Parse arguments form inputed string.

	Args:
		av (str): String to parse.

	Returns:
		Dict[str, Union[float, int, str, OptimizationType]]: Where key represents argument name and values it's value.

	See Also:
		* :func:`NiaPy.util.argparser.MakeArgParser`.
		* :func:`ArgumentParser.parse_args`
	"""
	parser = MakeArgParser()
	a = parser.parse_args(av)
	return a 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:18,代码来源:argparser.py

示例2: test_required_not_enforced

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def test_required_not_enforced(self):
        parser = GooeyParser()
        ArgumentParser.original_parse_args = ArgumentParser.parse_args

        parser.add_argument('--arg', type=int, required=True)
        parser.add_argument('--argn', type=int, nargs='+')
        parser.add_argument('argp', type=int)
        mutex=parser.add_mutually_exclusive_group(required=True)
        mutex.add_argument('--one', action='store_true')
        mutex.add_argument('--two', action='store_true')

        # No error when we don't provide required arguments
        cmd_args.parse_cmd_args(parser)

        # Test that required/argn have been restored in parser
        argrequired = next(action for action in parser._actions if action.dest == 'arg').required
        self.assertEqual(argrequired, True)
        argnnargs = next(action for action in parser._actions if action.dest == 'argn').nargs
        self.assertEqual(argnnargs, '+')
        argpnargs = next(action for action in parser._actions if action.dest == 'argp').nargs
        self.assertEqual(argpnargs, None)
        mutexrequired = next(mutex for mutex in parser._mutually_exclusive_groups).required
        self.assertEqual(mutexrequired, True) 
开发者ID:chriskiehl,项目名称:Gooey,代码行数:25,代码来源:test_cmd_args.py

示例3: test_cmd_args_subparser

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def test_cmd_args_subparser(self):
        parser = GooeyParser()
        subparsers = parser.add_subparsers(dest='subparser')
        subparserA = subparsers.add_parser('A')
        subparserB = subparsers.add_parser('B')
        subparserA.add_argument('argA', type=int, default=0)
        subparserB.add_argument('argB', type=int, default=0)

        ArgumentParser.original_parse_args = ArgumentParser.parse_args

        cmd_args.parse_cmd_args(parser, ['A', '1'])

        # Check that argA is overwritten but not argB
        subparseraction = next(action for action in parser._actions if action.dest == 'subparser')
        argAdefault = next(action for action in subparseraction.choices['A']._actions if action.dest == 'argA').default
        self.assertEqual(argAdefault, 1)
        argBdefault = next(action for action in subparseraction.choices['B']._actions if action.dest == 'argB').default
        self.assertEqual(argBdefault, 0) 
开发者ID:chriskiehl,项目名称:Gooey,代码行数:20,代码来源:test_cmd_args.py

示例4: parse_args

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def parse_args(self, *args, **kwargs):
        """Parse the arguments as usual, then add default processing."""
        if _debug: ConfigArgumentParser._debug("parse_args")

        # pass along to the parent class
        result_args = ArgumentParser.parse_args(self, *args, **kwargs)

        # read in the configuration file
        config = _ConfigParser()
        config.read(result_args.ini)
        if _debug: _log.debug("    - config: %r", config)

        # check for BACpypes section
        if not config.has_section('BACpypes'):
            raise RuntimeError("INI file with BACpypes section required")

        # convert the contents to an object
        ini_obj = type('ini', (object,), dict(config.items('BACpypes')))
        if _debug: _log.debug("    - ini_obj: %r", ini_obj)

        # add the object to the parsed arguments
        setattr(result_args, 'ini', ini_obj)

        # return what was parsed
        return result_args 
开发者ID:JoelBender,项目名称:bacpypes,代码行数:27,代码来源:consolelogging.py

示例5: parse_args

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def parse_args(self, extargs):
        self.parser = make_parser(self.aliases[0])
        opts = self.parser.parse_args(extargs)
        if opts.help_cmd:
            opts.action = 'help'
        elif opts.clean:
            # --clean is a deprecated fedup alias for clean
            if opts.action:
                raise CliError(NOT_TOGETHER % ('--clean', opts.action))
            if opts.network:
                raise CliError(NOT_TOGETHER % ('--clean', '--network'))
            opts.action = 'clean'
        elif opts.network:
            # --network is a deprecated fedup alias for download --releasever
            if opts.action:
                raise CliError(NOT_TOGETHER % ('--network', opts.action))
            if opts.releasever:
                raise CliError(NOT_TOGETHER % ('--network', '--releasever'))
            opts.releasever = opts.network
            opts.action = 'download'
        elif not opts.action:
            dnf.cli.commands.err_mini_usage(self.cli, self.cli.base.basecmd)
            raise CliError
        return opts 
开发者ID:rpm-software-management,项目名称:dnf-plugin-system-upgrade,代码行数:26,代码来源:system_upgrade.py

示例6: test_default_overwritten

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def test_default_overwritten(self):
        parser = GooeyParser()
        ArgumentParser.original_parse_args = ArgumentParser.parse_args

        parser.add_argument('arg', type=int, default=0)

        # Supply 1 as command line argument, check that it overwrites argparse default
        cmd_args.parse_cmd_args(parser, ['1'])
        argdefault = next(action for action in parser._actions if action.dest == 'arg').default
        self.assertEqual(argdefault, 1) 
开发者ID:chriskiehl,项目名称:Gooey,代码行数:12,代码来源:test_cmd_args.py

示例7: override_cli

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def override_cli(cli: Sequence[str] = ()):
    original_cli = ArgumentParser.parse_args

    try:
        ArgumentParser.parse_args = lambda self, _: original_cli(self, cli)

        yield None
    finally:
        ArgumentParser.parse_args = original_cli 
开发者ID:BranislavBajuzik,项目名称:ColorWallpaper,代码行数:11,代码来源:TestBase.py

示例8: configure

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def configure(self, args):
        self.opts = self.parse_args(args)
        self._call_sub("configure", args) 
开发者ID:rpm-software-management,项目名称:dnf-plugin-system-upgrade,代码行数:5,代码来源:system_upgrade.py

示例9: Gooey

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def Gooey(f=None,
          advanced=True,
          language='english',
          auto_start=False,  # TODO: add this to the docs. Used to be `show_config=True`
          program_name=None,
          program_description=None,
          default_size=(610, 530),
          required_cols=2,
          optional_cols=2,
          dump_build_config=False,
          load_build_config=None,
          monospace_display=False, # TODO: add this to the docs
          image_dir='default',
          language_dir=get_resource_path('languages'),
          progress_regex=None, # TODO: add this to the docs
          progress_expr=None, # TODO: add this to the docs
          disable_progress_bar_animation=False,
          disable_stop_button=False,
          group_by_type=True): # TODO: add this to the docs
  '''
  Decorator for client code's main function.
  Serializes argparse data to JSON for use with the Gooey front end
  '''

  params = locals()

  def build(payload):
    def run_gooey(self, args=None, namespace=None):
      source_path = sys.argv[0]

      build_spec = None
      if load_build_config:
        try:
          build_spec = json.load(open(load_build_config, "r"))
        except Exception, e:
          print( 'Exception loading Build Config from {0}: {1}'.format(load_build_config, e))
          sys.exit(1)

      if not build_spec:
        build_spec = config_generator.create_from_parser(self, source_path, payload_name=payload.__name__, **params)

      if dump_build_config:
        config_path = os.path.join(os.getcwd(), 'gooey_config.json')
        print 'Writing Build Config to: {}'.format(config_path)
        with open(config_path, 'w') as f:
          f.write(json.dumps(build_spec, indent=2))
      application.run(build_spec)

    def inner2(*args, **kwargs):
      ArgumentParser.original_parse_args = ArgumentParser.parse_args
      ArgumentParser.parse_args = run_gooey
      return payload(*args, **kwargs)

    inner2.__name__ = payload.__name__
    return inner2 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:57,代码来源:gooey_decorator.py

示例10: Gooey

# 需要导入模块: from argparse import ArgumentParser [as 别名]
# 或者: from argparse.ArgumentParser import parse_args [as 别名]
def Gooey(f=None,
          advanced=True,
          language='english',
          show_config=True,
          program_name=None,
          program_description=None,
          default_size=(610, 530),
          required_cols=2,
          optional_cols=2,
          dump_build_config=False,
          monospace_display=False):
  '''
  Decorator for client code's main function.
  Serializes argparse data to JSON for use with the Gooey front end
  '''

  params = locals()

  def build(payload):
    def run_gooey(self, args=None, namespace=None):
      source_path = sys.argv[0]
      build_spec = config_generator.create_from_parser(self, source_path, payload_name=payload.__name__, **params)

      if dump_build_config:
        config_path = os.path.join(os.getcwd(), 'gooey_config.json')
        print( 'Writing Build Config to: {}'.format(config_path))
        with open(config_path, 'w') as f:
          f.write(json.dumps(build_spec, indent=2))
      application.run(build_spec)

    def inner2(*args, **kwargs):
      ArgumentParser.original_parse_args = ArgumentParser.parse_args
      ArgumentParser.parse_args = run_gooey
      return payload(*args, **kwargs)

    inner2.__name__ = payload.__name__
    return inner2

  def run_without_gooey(func):
    return lambda: func()

  if IGNORE_COMMAND in sys.argv:
    sys.argv.remove(IGNORE_COMMAND)
    if callable(f):
      return run_without_gooey(f)
    return run_without_gooey

  if callable(f):
    return build(f)
  return build 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:52,代码来源:gooey_decorator.py


注:本文中的argparse.ArgumentParser.parse_args方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。