Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 does not do what I would like:

import argparse

parser = argparse.ArgumentParser(description="My parser") parser.add_argument("--my_bool", type=bool)

cmd_line = ["--my_bool", "False"]

parsed_args = parser.parse(cmd_line)

Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evaluates to False.

How can I get argparse to parse "False", "F", and their lower-case variants to be False?

1 Answer

0 votes
by (106k points)

For parsing boolean values with argparse a more canonical way would be to use --feature or --no-feature command:-

command --feature

and

command --no-feature

After running one of those commands you can use the following piece of code:-

parser.add_argument('--feature', dest='feature', action='store_true')

parser.add_argument('--no-feature', dest='feature', action='store_false')

parser.set_defaults(feature=True)

As you want the --arg <True|False> version, you can pass ast.literal_eval as the "type", or a user-defined function below-mentioned code explains the method how to do that:-

def t_or_f(arg):

     ua = str(arg).upper()

    if 'TRUE'.startswith(ua):

         return True

    elif 'FALSE'.startswith(ua):

         return False else:

            pass #Here you can write error condition.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...