Check if argparse optional argument is set or not

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

    I think that optional arguments (specified with --) are initialized to None if they are not supplied. So you can test with is not None. Try the example below:

    import argparse as ap
    
    def main():
        parser = ap.ArgumentParser(description="My Script")
        parser.add_argument("--myArg")
        args, leftovers = parser.parse_known_args()
    
        if args.myArg is not None:
            print "myArg has been set (value is %s)" % args.myArg
    

提交回复
热议问题