我知道這很像Setting default option in Python of two mutually exclusive options using the argparse module,儘管從不同的角度(以及給出的答案似乎沒有幫助)。如果另一個互斥參數爲真,則將默認值設置爲假
碼塊(解析器argparse.ArgumentParser的一個實例):
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_true",
dest="show", default=True)
mutex_group.add_argument("--insert", action="store_true",
dest="insert")
opts = parser.parse_args()
如果既未--show
或--insert
指定欲默認爲--show
(因此default=True
),但如果--insert
被使用,則opts.show
仍設置爲true(因爲默認),儘管它是互斥塊的一部分。
當前的代碼將檢查沒有其它選項已經被設置測試opt.show
是否屬實,當即:
if opts.show and not opts.insert:
do_something()
elif opts.insert:
do_something_else()
但這並不規模(會發生什麼,當你添加--delete
的互斥組等),所以我正在尋找一種更好的方式,使其他變量的默認值爲opts.show
,同時仍將其設置爲默認值。
閱讀argparse文檔,我認爲一個自定義操作將是路要走,但無法看到如何從內部訪問互斥組的其他成員(理論是我可以遍歷它們,並且如果其餘設置中的任何一個被設置,則翻轉默認值)。 另一種選擇是改變if條件,但似乎不清楚(如果默認更改,if語句的順序也必須改變)。