默认情况下Python Argparse"radio"标志?

Exe*_*n-G 2 python argparse

例如:

example.py

parser = argparse.ArgumentParser(description="Will take arguments... or none")

parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")

args = parser.parse_args()
print args
Run Code Online (Sandbox Code Playgroud)

我想将example.py设置aTrue,但仅限于:

  • 使用该-a标志
  • 没有使用标志

我试着乱搞

parser.set_defaults(a=True, b=False)

parser.add_argument("-a", action="store_true", default=True)

但他们将设置aTrue即使我决定使用的b标志.

gma*_*man 5

是的,使用默认值将a设置为True,甚至指定其他参数.这将违反您的第二个要求,以下是一个简单的修复与天真的条件检查.

parser = argparse.ArgumentParser(description="Will take arguments... or none")

parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")

args = parser.parse_args()
if not (args.b or args.c or args.d):
    args.a=True
print args
Run Code Online (Sandbox Code Playgroud)