简体   繁体   English

第一个 Python argparse 位置参数只能是 str 类型吗?

[英]Can first Python argparse positional argument only be of type str?

Am I right in the assumption that the first mandatory, positional argument added to argparse.ArgumentParser() instance can only be of type str ?我是否正确地假设添加到argparse.ArgumentParser()实例的第一个强制性位置参数只能是str类型?

When I set it to float (or int ) and run the script in a shell, I get an invalid float value error.当我将它设置为float (或int )并在 shell 中运行脚本时,我得到一个无效的浮点值错误。 I doesn't matter whether I really pass in a float or even call -h for help, which should skip the parameter input and jump straight to the help section.我是否真的传入float甚至调用-h寻求帮助都没有关系,这应该跳过参数输入并直接跳转到帮助部分。

import argparse

parser = argparse.ArgumentParser(
    prog="add-expense"
)

parser.add_argument(
    "Amount",
    type=float
)

args = parser.parse_args()

When I place another parser.add_argument() of default type str before it, everything works fine.当我在它之前放置另一个默认类型str parser.add_argument()时,一切正常。

With an added加上一个

print(args)

your script runs fine:你的脚本运行良好:

1013:~/mypy$ python3 stack69887099.py -h
usage: add-expense [-h] Amount

positional arguments:
  Amount

optional arguments:
  -h, --help  show this help message and exit
1013:~/mypy$ python3 stack69887099.py 1.232
Namespace(Amount=1.232)
1013:~/mypy$ python3 stack69887099.py test
usage: add-expense [-h] Amount
add-expense: error: argument Amount: invalid float value: 'test'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM