Python`argparse`:是否有一种干净的方法来添加设置多个标志的标志(例如,`--all`"等价于`--x --y`) [英] Python `argparse`: Is there a clean way to add a flag that sets multiple flags (e.g. `--all`" is equivalent to `--x --y`)

查看:34
本文介绍了Python`argparse`:是否有一种干净的方法来添加设置多个标志的标志(例如,`--all`"等价于`--x --y`)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 Python argparse 命令行处理代码,最初看起来像这样:

I've got some Python argparse command-line processing code that initially looked like this:

import argparse

ap = argparse.ArgumentParser()

ap.add_argument("--x", help = "Set `x`.", action = "store_true", default = False)
ap.add_argument("--y", help = "Set `y`.", action = "store_true", default = False)

ap.add_argument(
  "--all", help = "Equivalent to `--x --y`.",
  action = "store_true", default = False
)

args = ap.parse_args()

if args.all:
  args.x = True
  args.y = True

print "args.x", args.x
print "args.y", args.y

基本思想:我有一些布尔标志可以切换特定设置(--x--y 等),我想添加一个切换多个设置的便利选项 - 例如--all 等价于 --x --y.

The basic idea: I have some boolean flags that toggle on a particular setting (--x, --y, etc), and I want to add a convenience option that toggles multiple settings on - e.g. --all is equivalent to --x --y.

我想避免使用任何未包含在 ArgumentParser 中并在 parse_args 中完成的命令行处理逻辑,所以我想出了这个使用自定义 ArgumentParser 的解决方案代码>argparse.Actions:

I wanted to avoid having any command-line processing logic that was not contained within the ArgumentParser and done in parse_args, so I came up with this solution using custom argparse.Actions:

import argparse

def store_const_multiple(const, *destinations):
  """Returns an `argparse.Action` class that sets multiple argument
  destinations (`destinations`) to `const`."""
  class store_const_multiple_action(argparse.Action):
    def __init__(self, *args, **kwargs):
      super(store_const_multiple_action, self).__init__(
        metavar = None, nargs = 0, const = const, *args, **kwargs
      )

    def __call__(self, parser, namespace, values, option_string = None):
      for destination in destinations:
        setattr(namespace, destination, const)

  return store_const_multiple_action

def store_true_multiple(*destinations):
  """Returns an `argparse.Action` class that sets multiple argument
  destinations (`destinations`) to `True`."""
  return store_const_multiple(True, *destinations)

ap = argparse.ArgumentParser()

ap.add_argument("--x", help = "Set `x`.", action = "store_true", default = False)
ap.add_argument("--y", help = "Set `y`.", action = "store_true", default = False)

ap.add_argument(
  "--all", help = "Equivalent to `--x --y`.",
  action = store_true_multiple("x", "y")
)

args = ap.parse_args()

print "args.x", args.x
print "args.y", args.y

是否有任何干净的方法可以用 argparse 实现我想要的东西,而无需 (0) 在 parse_args()(第一个示例)或(2)编写之后进行一些处理自定义 argparse.Action(第二个示例)?

Is there any clean way of achieving what I want with argparse without either (0) doing some processing after parse_args() (first example) or (2) writing a custom argparse.Action (second example)?

推荐答案

这已经很晚了,不是您想要的,但您可以尝试以下方法:

This is late, and not exactly what you wanted, but here is something you could try:

import argparse

myflags = ['x', 'y', 'z']

parser = argparse.ArgumentParser()
parser.add_argument('--flags', nargs="+", choices=myflags)
parser.add_argument('--all-flags', action='store_const', const=myflags, dest='flags')
args = parser.parse_args()
print(args)

然后调用 python myscript.py --flags x y 输出这个

命名空间(flags=['x', 'y'])

并调用 python myscript.py --all-flags 输出这个

命名空间(flags=['x', 'y', 'z'])

但是你必须通过 'x' in args.flags 而不是简单的 args.x

But you'll have to check your flags via 'x' in args.flags instead of simply args.x

这篇关于Python`argparse`:是否有一种干净的方法来添加设置多个标志的标志(例如,`--all`"等价于`--x --y`)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆