728x90
반응형

 

 

아래와 같이 str2bool 함수를 구현하여 argparse 에서 boolean 값을 받아올 수 있다.

 

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.')

 

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='test')
    parser.add_argument('-b', '--boolean_flag', help='boolean flag', default=False, type=str2bool)
    args = parser.parse_args()

 

 

참고자료 : stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse

 

Parsing boolean values with argparse

I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: my_program --my_boolean_flag False However, the following test code doe...

stackoverflow.com

 

728x90
반응형