2012-11-09 39 views
6

我想有(例如)的腳本三個參數:如何限制我的python腳本只接受一個參數? (argparse)

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument("--a",help="Argument a") 
parser.add_argument("--b",help="Argument b") 
parser.add_argument("--c",help="Argument c") 
args= parser.parse_args() 

但讓這個只可能只指定是「A」,「B」或「C '在任何時間例如你可以指定'a'而不是'b'或'c'這是可能的,我將如何實現它?

回答

10

argpase讓您使用add_mutually_exclusive_group()方法指定此值。

import argparse 
parser = argparse.ArgumentParser() 
g = parser.add_mutually_exclusive_group() 
g.add_argument("--a",help="Argument a") 
g.add_argument("--b",help="Argument b") 
g.add_argument("--c",help="Argument c") 
args= parser.parse_args() 
+0

謝謝。正是我在找的東西。 – Sheldon

+1

@Alfe - 感謝您的編輯! – bgporter

1

使用上述add_mutually_exclusive_group()已經檢查了這對​​水平。

如果您想了解關於錯誤消息等更多的控制,當然你也可以稍後檢查結果:

if len([x for x in args.a, args.b, args.c if x is not None]) > 1: 
    raise Exception("Not allowed!") 
相關問題