Check if argparse optional argument is set or not

后端 未结 9 1524
臣服心动
臣服心动 2020-12-13 11:48

I would like to check whether an optional argparse argument has been set by the user or not.

Can I safely check using isset?

Something like this:

<         


        
9条回答
  •  春和景丽
    2020-12-13 12:29

    You can check an optionally passed flag with store_true and store_false argument action options:

    import argparse
    
    argparser = argparse.ArgumentParser()
    argparser.add_argument('-flag', dest='flag_exists', action='store_true')
    
    print argparser.parse_args([])
    # Namespace(flag_exists=False)
    print argparser.parse_args(['-flag'])
    # Namespace(flag_exists=True)
    

    This way, you don't have to worry about checking by conditional is not None. You simply check for True or False. Read more about these options in the docs here

提交回复
热议问题