TypeError: __init__() 在 argparse 中得到了一个意外的关键字参数“type"
嘿,我正在使用 argparse 来尝试生成季度报告.代码如下所示:
Hey so I'm using argparse to try and generate a quarterly report. This is what the code looks like:
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() 得到一个意外的关键字参数 'type'
TypeError: init() got an unexpected keyword argument 'type'
据我所知,argparse 文档类型是 add_argument 函数的参数之一.我尝试删除它并将代码更新为:
as far as I can tell from the argparse documentation type is one of the parameters of the add_argument function. I tried removing this and updating the code to :
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
运行它,它给了我以下错误:
I then tried to run it with: python scriptname.py -q 1 -y 2015
and it is giving me the following error:
错误:无法识别的参数:1 2015
error:unrecognized arguments: 1 2015
我也不知道为什么会这样.任何人都可以对此有所了解.
I don't know why that is either. Can anyone please shed some light on this.
action="store_true"
的意思是,如果参数在命令行中给出,则 True
code> value 应该存储在解析器中.您真正想要的是存储给定的年份(作为字符串)和季度(作为整数).
What action="store_true"
means is that if the argument is given on the command line then a True
value should be stored in the parser. What you actually want is to store the given year (as a string) and quarter (as an 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
参数(因为它将总是一个布尔值(真/假)).您不能同时提供 action="store_true"
和 'type'.
When you specify action='store_true
argparse is internally instantiating a _StoreAction
instance whose constructor does not accept a type
parameter (since it will always be a boolean (True/False)). You cannot supply action="store_true"
and 'type' at the same time.