2017-09-22 404 views
0

我在Python 3中使用​​將命令行參數接受到腳本中。在Python 3中使用argparse選擇多個可選參數

import argparse 

cli_argparser = argparse.ArgumentParser(description='') 
cli_argparser.add_argument('-n', '--number', type=int, help="Pass a number 'n' to script.", required=False) 
cli_argparser.add_argument('-q', '--query', help="Pass a query to the script", required=False) 
cli_argparser.add_argument('-o', '--outfile', help="Saves the output to an external file.", required=False) 
cli_args = cli_argparser.parse_args() 

if (cli_args.number): 
    print ("\n--number has the value '" + str(cli_args.number) + "'\n") 
elif (cli_args.query): 
    print ("\n--query has the value '" + cli_args.query + "'\n") 
elif (cli_args.outfile): 
    print ("\n--output has the value '" + cli_args.outfile + "'\n") 
else: 
    print ("\nNo Arguments passed. Set or Use a default value...\n") 

是否有辦法確保如果選擇了一個特定參數,則必須指定另一個參數?例如,如果指定-o,則在-o之前或之後還必須包含-n

我嘗試添加一個if條件,如下所示:

if (cli_args.number): 
    print ("\n--number has the value '" + str(cli_args.number) + "'\n") 
elif (cli_args.query): 
    print ("\n--query has the value '" + cli_args.query + "'\n") 
elif (cli_args.outfile): 
    if (cli_args.number): 
     print ("\n--output has the value '" + cli_args.outfile + "'\n") 
    else: 
     print ("\n--number not specified. Exit..") 
else: 
    print ("\nNo Arguments passed. Set or Use a default value...\n") 

結果是,如果只指定-o,腳本退出(如預期),然而,如果添加-n,第一條件是真的。

$ python test.py -o output.txt 

--number not specified. Exit.. 

$ python test.py -o output.txt -n 100 

--number has the value '100' 

我將如何修改這個使得如果只指定-n,第一個條件是真實的,如果指定-o,它需要-n過,然後執行第三個條件?會像cli_args.number AND cli_args.outfile工作?或者是否有內置功能​​?

+1

是的,你的'和'工作,你需要確保它是你的'if'鏈中的第一個條件,然而,或者把你當前的代碼移動到'outfile'塊頂部 –

+1

'argparse '沒有任何'包容性'測試。解析後的測試工作正常,特別是考慮到參數可以以任何順序出現。 'None'是一個很好的測試,因爲默認的'None'不能在命令行中出現。 – hpaulj

回答

0
elif (cli_args.outfile): 
    if (cli_args.number): 
     print ("\n--output has the value '" + cli_args.outfile + "'\n") 

邏輯的這個分支是在你的代碼無法訪問的時候cli_args.number是真實的,它會滿足你,如果... else分支的首要條件。

您可以先檢查outfile and number,或者您可以將第一個if語句中的邏輯更改爲if number and not outfile