Python optparse, 默认值与显式选项

6 投票
2 回答
8894 浏览
提问于 2025-04-17 05:50

下面是一个比较标准的代码:

from optparse import OptionParser                         
opts = OptionParser()
opts.add_option('-f', action="store_true")
opts.add_option("-x", dest="x", type="int", default=1)
options, args = opts.parse_args()

假设 -x-f 是互斥的:也就是说,当 -x-f 同时出现时,应该报错。

我该如何判断 -x 是否明确存在呢?即使它不存在,options 也会列出默认值。

一种方法是避免设置默认值,但我不太想这样做,因为 --help 可以很好地打印出默认值。

另一种方法是检查 sys.argv 中是否有 -x,不过如果 -x 有多个名称(比如说一个长名称)并且有多个互斥选项的话,这样做也有点麻烦。

有没有更优雅的解决方案呢?

2 个回答

9

你可以通过使用 optparse 和回调函数来实现这个功能。我们从你的代码开始:

from optparse import OptionParser

def set_x(option, opt, value, parser):
    parser.values.x = value
    parser.values.x_set_explicitly = True

opts = OptionParser()
opts.add_option('-f', action="store_true")
opts.add_option("-x", dest="x", type="int", default=1, action='callback',
                callback=set_x)
options, args = opts.parse_args()
opts.values.ensure_value('x_set_explicitly', False)

if options.x_set_explicitly and options.f:
    opts.error('options -x and -f are mutually exclusive')

我们暂时把这个脚本叫做 op.py。如果我运行 python op.py -x 1 -f,那么返回的信息是:

用法:op.py [选项]

op.py: 错误:选项 -x 和 -f 是互斥的

8

可以使用 argparse 这个库。里面有一个关于 互斥组 的部分:

argparse.add_mutually_exclusive_group(required=False)

这个方法可以创建一个互斥组。也就是说,argparse 会确保在命令行中,只能出现这个互斥组中的一个参数:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo

另外,optparse 这个库已经不推荐使用了。

撰写回答