2011-11-08 28 views
6

看看下面的相當標準代碼:Python的optparse,默認值和顯式選項

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(即--long名)以上的名稱和有不止一對相互排斥的選項。

它有一個優雅的解決方案嗎?

回答

7

使用argparse。有一個爲mutually exclusive groups節:

argparse.add_mutually_exclusive_group(required=False)

Create a mutually exclusive group. argparse will make sure that only one of the arguments in the mutually exclusive group was present on the command line:

>>> 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反正是不推薦使用。

8

您可以用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,則迴應是:

Usage: op.py [options]

op.py: error: options -x and -f are mutually exclusive