Boolean argument for script

In Python, I understand how int and str arguments can be added to scripts.

parser=argparse.ArgumentParser(description="""Mydescription""") parser.add_argument('-l', type=str, default='info', help='String argument') parser.add_argument('-dt', type=int, default ='', help='int argument') 

What are these booleans?

Basically, I want to pass a flag to my script, which tells the script whether to do something or not.

+68
python
Feb 07 2018-12-12T00:
source share
3 answers

You can use action with store_true | store_false , or you can use int and allow implicit casting to check the boolean value.

Using action , you will not pass the argument --foo=true and --foo=false , you just enable it if it should be set to true.

 python myProgram.py --foo 

In fact, I think you might need

 parser.add_argument('-b', action='store_true', default=False) 
+132
Feb 07 2018-12-21T00:
source share
 parser.add_argument('--foo', action='store_true') 
+15
Feb 07 2018-12-21T00:
source share
 import distutils.util ARGP.add_argument('--on', '-o', type=distutils.util.strtobool, default='true') 

Example:

 $ ./myscript # argp.on = 1 $ ./myscript --on=false # argp.on = 0 $ ./myscript --on=False # argp.on = 0 $ ./myscript --on=0 # argp.on = 0 $ ./myscript --on=1 # argp.on = 1 $ ./myscript -o0 # argp.on = 0 $ ./myscript -o false # argp.on == 0 

I should mention, you can also associate an argument with a local wrapper function to handle some other exact string matches if you want to support values ​​like yes and no. you can also try to interpret the input as yaml, which can handle yes / no. I haven't done this for a while though, and I think lately I have sucked mutually exclusive arguments with the same dest value, one --no-option with action='store_false' and one --option with action='store_true'

+2
Aug 15 '16 at 1:39 on
source share



All Articles