Python — argparse parse bool value

Time:2021-11-25

preface

In a code that needs to use flag as a signal to control whether some code fragments run, such as “– flag true” or “– flag false”.

But the odd thing is that you can’t pass in false. Whether you pass in true or false, there are true parameters in the program, so this flag doesn’t take effect and loses its meaning.

Reference code:

# test.py
import argparse


def test_bool():
    parser = argparse.ArgumentParser(description="This code is used to test bool value.")
    parser.add_argument("--flag",
                        type=bool,
                        default=True)
    args = parser.parse_args()
    print("# The type of flag: ", type(args.flag))
    print(args.flag is False)

    if args.flag:
        print(f"# Flag: {True}")
    else:
        print(f"# Flag: {False}")


if __name__ == '__main__':
    test_bool()

Execute the above code:python3 test.py --flag False

According to the expectation of execution is output# Flag: FalseBut the actual output isTrue

(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag False
# The type of flag:  <class 'bool'>
False
# Flag: True

Why does this happen? Because the input on the command line will be regarded by Python as a string, not a boolean type.

Solution 1 [recommended]

Change the code to:

# ***
parser.add_argument("--flag",
                        action="store_true",
                        help="Run or not.")
# ***

In that case, when you don’t enter--flagThe default value isFalse; input--flagIt will be triggered whenTrueValue.

See the execution results:

(data_parse)  ~/Desktop/code/cython&numba  python3 test.py
# The type of flag:  <class 'bool'>
True
# Flag: False
(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag
# The type of flag:  <class 'bool'>
False
# Flag: True

Of course, in this way, you can also specify action asstore_false, when not input--flagdefaultTrue, enter--flagtriggerFalse

Solution 2

This method is a little more complicated, that is, you need to write a function to convert the input string value from string to Boolean value.

code:

import argparse


def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')


def test_bool():
    parser = argparse.ArgumentParser(description="This code is used to test bool value.")
    parser.add_argument("--flag",
                        type=str2bool,
                        default=True,
                        help="Run or not.")
    args = parser.parse_args()
    print("# The type of flag: ", type(args.flag))
    print(args.flag is False)
    if args.flag:
        print(f"# Flag: {True}")
    else:
        print(f"# Flag: {False}")


if __name__ == '__main__':
    test_bool()

In this case, when we just enter the corresponding values in the custom functionTrueorFalseCan trigger the corresponding boolean type.

Depending on the implementation:

(data_parse)  ~/Desktop/code/cython&numba  python3 test.py         
# The type of flag:  <class 'bool'>
False
# Flag: True
(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag True
# The type of flag:  <class 'bool'>
False
# Flag: True
(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag False
# The type of flag:  <class 'bool'>
True
# Flag: False
(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag 0    
# The type of flag:  <class 'bool'>
True
# Flag: False
(data_parse)  ~/Desktop/code/cython&numba  python3 test.py --flag 1
# The type of flag:  <class 'bool'>
False
# Flag: True

Because defaultdefaultThe value of isTrue, so do not enter--flagThe default isTrue, and then enter--flagCorresponding customizationfunc: str2bool()The desired switching effect can be achieved.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]