Here is the simplest Python script, named test.py:
import argparse parser = argparse.ArgumentParser() parser.add_argument('--bool', default=True, type=bool, help='Bool type') args = parser.parse_args() print(args.bool)
But when I run this code on the command line:
python test.py --bool False True
Whereas when my code reads '--bool', default=False
, the argparse runs correctly.
Why?
The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.
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.
Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
const is the value it gets when given.
You are not passing in the False
object. You are passing in the 'False'
string, and that's a string of non-zero length.
Only a string of length 0 tests as false:
>>> bool('') False >>> bool('Any other string is True') True >>> bool('False') # this includes the string 'False' True
Use a store_true
or store_false
action instead. For default=True
, use store_false
:
parser.add_argument('--bool', default=True, action='store_false', help='Bool type')
Now omitting the switch sets args.bool
to True
, using --bool
(with no further argument) sets args.bool
to False
:
python test.py True python test.py --bool False
If you must parse a string with True
or False
in it, you'll have to do so explicitly:
def boolean_string(s): if s not in {'False', 'True'}: raise ValueError('Not a valid boolean string') return s == 'True'
and use that as the conversion argument:
parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')
at which point --bool False
will work as you expect it to.
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