I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument --head
. This is the functionality I'd like it to have:
When --head
is not passed at the command line I'd like it to default to one value. In this case, a rather big one, like 80
When --head
is passed without any value, I'd like it to default to another value. In this case, something limited, like 10
When --head
is passed with a value, I'd like it to store the value it was passed.
Here is some code describing the problem:
>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-h', '--head', dest='size', const=80, default=10, action="I don't know", help='Only print the head of the output') >>> # OFC, that last line will fail because the action is uknown, ... # but here is how I'd like it to work ... parser.parse_args(''.split()) Namespace(size=80) >>> parser.parse_args('--head'.split()) Namespace(size=10) >>> parser.parse_args('--head 15'.split()) Namespace(size=15)
I know I probably can write a custom action for this, but I first want to see if there is any default behaviour that does this.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self. 😃 Using argparse means the doesn't need to go into the code and make changes to the script.
After a little more reading in the documentation I found what I needed: nargs='?'
. This is used with the store
action, and does exactly what I want.
Here is an example:
>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--head', dest='size', const=10, default=80, action='store', nargs='?', type=int, help='Only print the head of the output') >>> parser.parse_args(''.split()) ... Namespace(size=80) >>> parser.parse_args('--head'.split()) ... Namespace(size=10) >>> parser.parse_args('--head 15'.split()) ... Namespace(size=15)
Source: http://docs.python.org/3/library/argparse.html#nargs
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