检查某些参数并将值分配给任意变量

Check for certain arguments and assign values to an arbitrary variable

我正在编写一个程序,需要查找在命令行上设置的两个参数之一,并根据设置的参数将值保存到单个变量。

如果我这样调用程序:

myprogram -a --foo 123

我想将变量 action 设置为 'a value'。像这样称呼它:

myprogram -b --foo 123

并且action应该设置为'another value'。两者都不调用它:

myprogram -c --foo 123

它应该退出并显示使用信息。

显然我可以在事后用一些 if 语句来做到这一点:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='count')
parser.add_argument('-b', action='count')
parser.add_argument('--foo')
....
args = parser.parse_args()
if args.a == 0 and args.b == 0:
    parser.print_usage()
    sys.exit(1)
if args.a > 0:
    action = 'a value'
elif args.b > 0:
    action = 'another value'

但我想知道 argparse 是否可以用更少的代码为我做这件事。从我在文档中看到的情况来看,这是不可能的,但是 Python 对我来说是非常新的。谢谢。

看看action='store_const'.

In [240]: parser=argparse.ArgumentParser()
In [241]: parser.add_argument('-a', dest='action',
   action='store_const', const='a value')
In [242]: parser.add_argument('-b', dest='action',
   action='store_const', const='another value')
In [243]: parser.add_argument('--foo')

In [244]: parser.parse_args('-a --foo 123'.split())
Out[244]: Namespace(action='a value', foo='123')

In [245]: parser.parse_args('-b --foo 123'.split())
Out[245]: Namespace(action='another value', foo='123')

In [246]: parser.parse_args('-c --foo 123'.split())
usage: ipython3 [-h] [-a] [-b] [--foo FOO] 
ipython3: error: unrecognized arguments: -c
SystemExit: 2

因此 args.action 将具有 a value' orb 值',具体取决于参数。注意 -a-b 存储到相同的 dest.

我没有定义 -c,所以它使用正常的 undefined 退出。可以改进。

像这样定义 c 可以让您自己退出:

In [247]: parser.add_argument('-c', dest='action', action='store_const', const='exit')

In [248]: args=parser.parse_args('-c --foo 123'.split())
In [249]: if args.action=='exit':parser.print_usage()
usage: ipython3 [-h] [-a] [-b] [--foo FOO] [-c]

如果您使用 action='store_true' 而不是 'count' 作为 -a-b,您可以将 if 树简化为:

if args.a:
    action = 'a value'
elif args.b:
    action = 'another value'
else:
    parser.print_usage()
    sys.exit(1)

我使用了 hapulj 的回答,但仍然以 if 语句结束,以检查两者是否均未设置。然后我找到了 ArgumentParser.add_mutually_exclusive_group() 函数,最后得到了这个,效果很好。

import argparse
parser = argparse.ArgumentParser()
actiongroup = parser.add_mutually_exclusive_group(required=True)
actiongroup.add_argument('-a', action='store_const', dest='action', const='a value')
actiongroup.add_argument('-b', action='store_const', dest='action', const='another value')
parser.add_argument('--foo')
....
args = parser.parse_args()

现在,参数-a-b不能省略,也不能同时指定。