在Python 3中使用argparse选择多个可选参数
问题描述:
我在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
工作?或者是否有内置功能?
答
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
。
是的,你的'和'工作,你需要确保它是你的'if'链中的第一个条件,然而,或者把你当前的代码移动到'outfile'块顶部 –
'argparse '没有任何'包容性'测试。解析后的测试工作正常,特别是考虑到参数可以以任何顺序出现。 'None'是一个很好的测试,因为默认的'None'不能在命令行中出现。 – hpaulj