在optparse中可以强制选项为必填项吗?

10 投票
3 回答
10690 浏览
提问于 2025-04-16 09:22

在optparse中,可以把某个选项设置成必须填写的吗?

3 个回答

2

不,你不能这样做。你可以使用 argparse 这个工具,或者使用 optparse 模块来获取选项的值,然后明确检查这个选项的值是否被定义(比如在 optparse 中把它设置为默认值,比如 None,然后检查它是不是 None)。如果没有定义,就调用 sys.exit(),提示用户提供这个选项。

8

选项本身就是可选的 :-) 如果你想要让某个参数变成必填的,可以使用 argparse 这个工具,并设置一个位置参数。

http://docs.python.org/dev/library/argparse.html

20

我之前发过一个评论,但因为很多其他回答都说 No, not possible,所以我来告诉你怎么做:

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

这样就把 -f 变成了必须要用的选项。

确实可以用 argparse 来实现这个功能,但这并不意味着你不能在 optparse 中做到这一点。

撰写回答