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

前端 未结 9 2046
走了就别回头了
走了就别回头了 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:28

    The current answer with the most votes would not work if, for example, the argument were an integer or float for which zero is a valid input. In these cases it would say that there is an error. An alternative (to add to the several others here) would be to do e.g.

    parser = OptionParser(usage='usage: %prog [options] arguments')
    parser.add_option('-f', '--file', dest='filename')
    (options, args) = parser.parse_args()
    if 'filename' not in options.__dict__:
      parser.error('Filename not given')
    

提交回复
热议问题