編輯:沒關係。因爲使得在調用group.add_argument
時必須創建選項的可怕選擇。那不會是我的設計選擇。如果此功能是絕望的,你可以嘗試用ConflictsOptionParser做:
# exclusivegroups.py
import conflictsparse
parser = conflictsparse.ConflictsOptionParser()
a_opt = parser.add_option('-a')
b_opt = parser.add_option('-b')
c_opt = parser.add_option('-c')
d_opt = parser.add_option('-d')
import itertools
compatible_opts1 = (a_opt, b_opt)
compatible_opts2 = (c_opt, d_opt)
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
parser.register_conflict(exclusive_grp)
opts, args = parser.parse_args()
print "opts: ", opts
print "args: ", args
因此,當我們調用它,我們可以看到,我們得到想要的效果。
$ python exclusivegroups.py -a 1 -b 2
opts: {'a': '1', 'c': None, 'b': '2', 'd': None}
args: []
$ python exclusivegroups.py -c 3 -d 2
opts: {'a': None, 'c': '3', 'b': None, 'd': '2'}
args: []
$ python exclusivegroups.py -a 1 -b 2 -c 3
Usage: exclusivegroups.py [options]
exclusivegroups.py: error: -b, -c are incompatible options.
警告消息不會通知您,無論'-a'
和'-b'
與'-c'
不兼容,但是一個更合適的錯誤信息,可以製作。下面的老的,錯誤的答案。
OLDER編輯:[編輯這是錯誤的,但不會是隻是一個完美的世界,如果曾這樣?]我以前的答案其實是不正確的,你應該能夠做到這一點通過爲每個互斥選項指定一個組。我們甚至可以使用itertools
來概括過程。並且做它,因此我們不必明確地輸出所有組合:
import itertools
compatible_opts1 = ('-a', '-b')
compatible_opts2 = ('-c', '-d')
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
group = parser.add_mutually_exclusive_group()
group.add_argument(exclusive_grp[0])
group.add_argument(exclusive_grp[1])
http://bugs.python.org/issue10984有一個修補程序,可讓您將參數放入多個互斥組中。這是一個簡單的改變。使用重疊組生成有意義的用法更爲重要。 – hpaulj 2013-08-09 05:02:33