4
我有一个测试的代码如下相互排斥的群体,即应采取要么位置参数file
或全部可选参数time
,expression
和name
:如何让argparse检查参数
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-t","--time")
parser.add_argument("-x","--expression")
parser.add_argument("-n","--name")
parser.add_argument("file")
print parser.parse_args()
以下组合应该工作
test.py filename
test.py -t 5 -x foo -n test
但不是这些:
test.py filename -t 5 # should raise error because the positional and the optional -t argument cannot be used together
test.py -t 5 -x foo # should raise an error because all three of the optional arguments are required
该问题的任何简单解决方案?
@Mathan:我想出了执行所提供的参数的手动检查类似的解决方案。我希望有一个(i)argparse独立解决方案和(ii)解决方案,当提供文件时不指定'--file' <后一个要求在我的方法中解决>。 – Alex 2013-04-04 08:04:43
我不认为'argparse'是那么复杂。它确实有一个'add_mutually_exclusive_group'函数,但它确保提供了一组参数中最多一个参数。 – 2013-04-04 08:12:59
我担心是这样。但是我想给这个问题一个改变,无论如何...感谢你的方法。 – Alex 2013-04-04 08:14:55