dublintech
dublintech

Reputation: 17785

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.

Upvotes: 85

Views: 60153

Answers (4)

mausamsion
mausamsion

Reputation: 230

import argparse
if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--bool_flag', type=str)
    args = parser.parse_args()
    args.bool_flag = bool(eval(args.bool_flag))
    print(args.bool_flag, ',', type(args.bool_flag))

For the above python code saved as tmp.py:

python tmp.py --bool_flag '0' gives False , <class 'bool'>

python tmp.py --bool_flag 'False' gives False , <class 'bool'>

python tmp.py --bool_flag '1' gives True , <class 'bool'>

python tmp.py --bool_flag 'True' gives True , <class 'bool'>

Calling above code from a shell script would work too,

#!/bin/bash
flag=False
python tmp.py --bool_flag $flag

This will give the output: False , <class 'bool'>

Upvotes: 0

ThorSummoner
ThorSummoner

Reputation: 18099

import distutils.util
ARGP.add_argument('--on', '-o', type=distutils.util.strtobool, default='true')

Example calling it:

$ ./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 bind the argument to a local wrapper function too, to handle some other exact string matching if you want to support values like "yes" and "no". you can also try interpreting the input as yaml, which can handle yes/no too. i haven't done this in a while though, and i think lately I've suck to mutually exclusive arguments with the same dest value, one --no-option with action='store_false', and one --option with action='store_true'

Upvotes: 10

sberry
sberry

Reputation: 131978

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)

Upvotes: 160

Ned Batchelder
Ned Batchelder

Reputation: 375494

parser.add_argument('--foo', action='store_true')

Upvotes: 21

Related Questions