python - 类型错误 : __init__() got an unexpected keyword argument 'type' in argparse

标签 python parsing argparse

嘿,所以我正在使用 argparse 来尝试生成季度报告。代码是这样的:

parser  = argparse.ArgumentParser()

parser.add_argument('-q', "--quarter",  action='store_true', type=int, help="Enter a Quarter number: 1,2,3, or 4 ")
parser.add_argument('-y', "--year", action='store_true',type=str,help="Enter a year in the format YYYY ")
args = parser.parse_args()

我收到的错误是:

TypeError: init() got an unexpected keyword argument 'type'

据我所知,argparse 文档类型是 add_argument 函数的参数之一。我尝试删除它并将代码更新为:

parser  = argparse.ArgumentParser()

parser.add_argument('-q', "--quarter",  action='store_true', help="Enter a Quarter number: 1,2,3, or 4 ")
parser.add_argument('-y', "--year", action='store_true',help="Enter a year in the format YYYY ")
args = parser.parse_args()

然后我尝试使用以下命令运行它:python scriptname.py -q 1 -y 2015 它给了我以下错误:

error:unrecognized arguments: 1 2015

我也不知道为什么。任何人都可以对此有所了解。

最佳答案

action="store_true" 的意思是,如果在命令行中给出参数,那么 True 值应该存储在解析器中。您真正想要的是存储给定的年份(作为字符串)和季度(作为 int)。

parser  = argparse.ArgumentParser()

parser.add_argument('-q', "--quarter", type=int, help="Enter a Quarter number: 1,2,3, or 4 ")
parser.add_argument('-y', "--year", type=str, help="Enter a year in the format YYYY ")
args = parser.parse_args()

当您指定 action='store_true 时,argparse 在内部实例化一个 _StoreAction 实例,其构造函数不接受 type 参数(因为它会始终为 bool 值(真/假))。您不能同时提供 action="store_true" 和 'type'。

关于python - 类型错误 : __init__() got an unexpected keyword argument 'type' in argparse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33574270/

相关文章:

C - 使用 sscanf 忽略空格

python - 将 sys.stdout.write 输出添加到变量

java - Java 的 SQL 解析器库

python-3.x - 错误 : argument are required -i/--image

python - 在 Python 中以高精度计算 e(自然对数的底数)?

python - 在 python 中附加 2 个十六进制值

python - argParse 新手,不确定我的错误在哪里

Python argparse 忽略默认值

python - matplotlib生成动画,每个文件都是一个新帧

python - 如何进行无限线程评论