Python: How to make an option to be required in optparse?

前端 未结 9 2024
走了就别回头了
走了就别回头了 2021-02-05 00:57

I\'ve read this http://docs.python.org/release/2.6.2/library/optparse.html

But I\'m not so clear how to make an option to be required in optparse?

I\'ve tried to

9条回答
  •  别那么骄傲
    2021-02-05 01:32

    Since if not x doesn't work for some(negative,zero) parameters,

    and to prevent lots of if tests, i preferr something like this:

    required="host username password".split()
    
    parser = OptionParser()
    parser.add_option("-H", '--host', dest='host')
    parser.add_option("-U", '--user', dest='username')
    parser.add_option("-P", '--pass', dest='password')
    parser.add_option("-s", '--ssl',  dest='ssl',help="optional usage of ssl")
    
    (options, args) = parser.parse_args()
    
    for r in required:
        if options.__dict__[r] is None:
            parser.error("parameter %s required"%r)
    

提交回复
热议问题