Check if argparse optional argument is set or not

后端 未结 9 1518
臣服心动
臣服心动 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:27

    Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...

    if args.argument_name:
       # do something
    else:
       # do something else
    
    0 讨论(0)
  • 2020-12-13 12:28

    As @Honza notes is None is a good test. It's the default default, and the user can't give you a string that duplicates it.

    You can specify another default='mydefaultvalue, and test for that. But what if the user specifies that string? Does that count as setting or not?

    You can also specify default=argparse.SUPPRESS. Then if the user does not use the argument, it will not appear in the args namespace. But testing that might be more complicated:

    args.foo # raises an AttributeError
    hasattr(args, 'foo')  # returns False
    getattr(args, 'foo', 'other') # returns 'other'
    

    Internally the parser keeps a list of seen_actions, and uses it for 'required' and 'mutually_exclusive' testing. But it isn't available to you out side of parse_args.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题