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
值.您真正想要的是将给定的年份(作为字符串)和季度(作为整数)存储.
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.