dublintech dublintech - 3 months ago 9
Python Question

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 is it for booleans?

Basically I want to pass a flag into my script which will tell the script whether to do a specific action or not.

Answer

You can either use the action with store_true|store_false, or you can use an int and let implicit casting check a boolean value.

Using the action, you wouldn't pass a --foo=true and --foo=false argument, you would simply include it if it was to be set to true.

python myProgram.py --foo

In fact I think what you may want is

parser.add_argument('-b', action='store_true', default=False)
Comments