argparse不检查位置参数 [英] argparse doesn't check for positional arguments
问题描述
我正在创建一个脚本,该脚本同时使用argparse的位置参数和可选参数.我已经阅读了Doug的教程和python文档,但是找不到答案.
I'm creating a script that takes both positional and optional arguments with argparse. I have gone through Doug's tutorial and the python Docs but can't find an answer.
parser = argparse.ArgumentParser(description='script to run')
parser.add_argument('inputFile', nargs='?', type=argparse.FileType('rt'),
parser.add_argument('inputString', action='store', nargs='?')
parser.add_argument('-option1', metavar='percent', type=float, action='store')
parser.add_argument('-option2', metavar='outFile1', type=argparse.FileType('w'),
parser.add_argument('-option3', action='store', default='<10',
args = parser.parse_args()
# rest of script.... blah blah
如您所见,我想要2个位置参数和3个可选参数.但是,当我尝试在终端中运行它时,它不会检查位置信息! 如果我尝试:python script.py inputfile 如果找不到inputString的值,它将正常运行并在脚本的一半输出错误. 如果我尝试:python script.py xxx;输出为:
As you can see, I want 2 positional and 3 optional arguments. However, when I try to run it in the terminal, it doesn't check for the positionals! If I try: python script.py inputfile it will run normally and output error halfway through the script when it cannot find a value for inputString. If I try: python script.py xxx ; the output is:
usage script.py [-h] [-option1] [-option2] [-option3]
任何人都可以解释为什么它不检查位置参数吗?
Can anyone explain why it doesn't check for the positional arguments?
推荐答案
您的问题是您指定了nargs='?'
.从文档:
Your problem is that you're specifying nargs='?'
. From the documentation:
'?'
.如果可能,将从命令行使用一个参数,并将其作为单个项目产生.如果不存在命令行参数,则将生成默认值.
'?'
. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.
如果省略了nargs='?'
,则将需要该参数,如果未提供,则argparse
将显示错误.如果action='store'
(默认值),则使用单个参数.
If you leave out the nargs='?'
then the argument will be required, and argparse
will display an error if it is not provided. A single argument is consumed if action='store'
(the default).
您也可以指定nargs=1
;不同之处在于,这将产生一个包含一个项目的列表,而不是该项目本身.有关使用nargs
的更多方法,请参见文档.
You can also specify nargs=1
; the difference is that this produces a list containing one item, as opposed to the item itself. See the documentation for more ways you can use nargs
.
这篇关于argparse不检查位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!