2017-09-17 55 views
0

我正在設計一個基於argparse的命令行程序,並且必須提出的一個參數要求用戶從輸出圖形格式的總共三個選項中選擇一個或多個。如果用戶在命令行中沒有提到這個參數,那麼默認情況下,這個參數輸出所有三種類型的輸出圖。如何在一個argparse參數中有效地選擇一個,兩個或三個選擇?

所以,爭論本身看起來或多或少是這樣的:

import argparse 

if __name__ == "__main__": 
    BobsProgram = argparse.ArgumentParser(prog= "BobsProgram") 
    BobsProgram.description= "This code analyzes these inputs, and will output one or more graphs of your choosing." 

    BobsProgram.add_argument("-output_graph", choices= ["pie", "bar", "scatter"], default= all, nargs= "+", 
    help= "Unless otherwise indicated, the output graphs will be given in the pie, bar, and scatter forms.") 

所以,當我跑了args= BobsProgram.parse_args()線,並開始派遣我的論點,我想它設置,使用戶可以輸入他們的選擇是爲了他們想要的。我只發現有可能使命令行程序功能時,我建立了七個條件塊:

if args.output_graph == ["pie"]: 
    ##format the output file as a pie chart 
elif args.output_graph == ["bar"]: 
    ##format the output file as a bar chart 
elif args.output_graph == ["scatter"]: 
    ##format the output as a scatter chart 
elif args.output_graph == ["pie","bar"] and ["bar", "pie"]: 
    ##format the output as pie and bar charts 
elif args.output_graph == ["pie","scatter"] and ["scatter","pie"]: 
    ##format the output as pie and scatter charts 
elif args.output_graph == ["bar", "scatter"] and ["scatter","bar"]: 
    ##format the output as bar and scatter charts 
else: 
    ##format the output as bar, pie, and scatter charts 

最終,雖然代碼工作,它似乎並不十分Python的,因爲我必須複製了很多每個條件塊內都有相同的代碼。我如何修改這個以使其更有效率?

+0

不要擔心效率。解析器在腳本開始時運行一次。更重要的是用戶友好和清晰。什麼是「全部」?考慮像args.output_graph中的'bar'這樣的測試(因爲該屬性是這些字符串的列表)。但是,這不會響應用戶的訂單。 – hpaulj

+0

@hpaulj'all'是一個關鍵字,根據我的理解,它封裝了所有提供的選項。另外,通過測試「bar」,你的意思是什麼? –

+0

'all'不是'argparse'關鍵字。如果將其定義爲選項列表,則可能有意義。 – hpaulj

回答

1

如果訂單不那麼重要,你可以這樣做:

alist = args.your_name 
if 'foo' in alist: 
    # do foo 
elif 'bar' in alist: 
    # do bar 
# etc 

如果用戶提供的順序問題則是這樣的:

for fn in alist: 
    if fn in ['foo']: # or `fn == 'foo'` 
     # do foo 
    elif fn in ['bar']: 
     # do bar 
1

我會做這樣的事情:

for arg in args.output_graph: 
    if arg == 'pie': 
     #add_pie_chart() 
    if arg == 'bar': 
     #add_bar_chart() 
    if arg == 'scatter': 
     #add_scatter_plot() 

圖形功能現在只調用一次爲每個圖表。只要您的添加圖表函數相互之間相對較好,即在顯示結果之前全部添加到主畫布,這應該工作。

相關問題