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()
the error I receive is:
TypeError: init() got an unexpected keyword argument 'type'
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()
I then tried to run it with: python scriptname.py -q 1 -y 2015
and it is giving me the following error:
error:unrecognized arguments: 1 2015
I don't know why that is either. Can anyone please shed some light on this.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With