2011-11-08 25 views
6

Hãy mã chứ không phải tiêu chuẩn sau đây:Python optparse, giá trị mặc định, và các tùy chọn rõ ràng

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() 

Giả sử rằng -x-f loại trừ lẫn nhau: khi -x-f đều có mặt một cách rõ ràng, một lỗi nên được báo cáo.

Làm cách nào để phát hiện xem -x có hiển thị rõ ràng không? Ngay cả khi không, options liệt kê giá trị mặc định.

Có một cách để tránh đặt giá trị mặc định mà tôi không muốn làm vì --help in giá trị mặc định một cách độc đáo.

Một cách khác sẽ được kiểm tra sys.argv cho trường hợp của -x đó là một chút vụng về, quá, nếu có nhiều hơn một tên cho -x (có nghĩa là, một --long-name) và có nhiều hơn một cặp loại trừ lẫn nhau tùy chọn.

Nó có một giải pháp thanh lịch cho điều này?

Trả lời

7

Sử dụng argparse. Có một phần dành cho 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 bị phản anyway.

8

Bạn có thể thực hiện việc này với optparse bằng cách sử dụng gọi lại. Xây dựng từ mã của bạn:

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') 

Hãy gọi mã này op.py bây giờ. Nếu tôi làm python op.py -x 1 -f, phản hồi là:

Usage: op.py [options]

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

Các vấn đề liên quan