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
工作?或者是否有內置功能?
是的,你的'和'工作,你需要確保它是你的'if'鏈中的第一個條件,然而,或者把你當前的代碼移動到'outfile'塊頂部 –
'argparse '沒有任何'包容性'測試。解析後的測試工作正常,特別是考慮到參數可以以任何順序出現。 'None'是一個很好的測試,因爲默認的'None'不能在命令行中出現。 – hpaulj