argparse 不检查位置参数 [英] argparse doesn't check for positional arguments

查看:34
本文介绍了argparse 不检查位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个脚本,它采用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆