添加以“ h”开头的参数

时间:2018-12-16 14:35:35

标签: python

使用此代码,我似乎无法添加“ --height”作为参数,因为Python与默认选项“ -h / --help”混淆了。创建对象时,我尝试添加add_help=False,但仍然出现错误main.py: error: the following arguments are required: height

import argparse

parser = argparse.ArgumentParser(description='my description')
parser.add_argument('height', type=int, nargs=1)

args = parser.parse_args()

1 个答案:

答案 0 :(得分:5)

您创建了位置参数。 argparse的工作方式是,当您定义一个不带任何前导---的参数时,它将被认为是位置正确的,因此您必须像python yourscript.py the_height这样调用脚本。

如果您想像python myscript.py --height 222那样称呼它,则必须这样做

parser.add_argument("--height", action="store")
args_namespace = parser.parse_args()
print(args_namespace.height)