Synopsis - Synopsis/getoptions.py

File: Synopsis/getoptions.py

     1#
     2# Copyright (C) 2003 Stefan Seefeld
     3# All rights reserved.
     4# Licensed to the public under the terms of the GNU LGPL (>= 2),
     5# see the file COPYING for details.
     6#
     7
     8from __future__ import generators
     9from Processor import Error
    10import sys
    11
    12class CommandLineError(Error): pass
    13
    14def parse_option(arg):
    15    """The required format is '--option[=[arg]]' or 'option=arg'.
    16    In the former case the optional argument is interpreted as
    17    a string (only '--option' sets the value to True, '--option='
    18    sets it to the empty string), in the latter case the argument
    19    is evaluated as a python expression.
    20    Returns (None, None) for non-option argument"""
    21
    22    if arg.find('=') == -1 and not arg.startswith('--'):
    23        return None, None # we are done
    24    attribute = arg.split('=', 1)
    25    if len(attribute) == 2:
    26        name, value = attribute
    27        if name.startswith('--'):
    28            name = name[2:] # value is a string
    29        else:
    30            try:
    31                value = eval(value) # it's a python expression
    32            except:
    33                sys.stderr.write("""an error occured trying to evaluate the value of \'%s\' (\'%s\')
    34to pass this as a string, please use %s="'%s'" \n"""%(name, value, name, value))
    35                sys.exit(-1)
    36    else:
    37        name, value = attribute[0][2:], True # flag the attribute as 'set'
    38
    39    return name, value
    40
    41
    42def get_options(args, parse_arg = parse_option, expect_non_options = True):
    43    """provide an iterator over the options in args.
    44    All found options are stripped, such that args will
    45    contain the remainder, i.e. non-option arguments.
    46    Pass each argument to the parse_option function to
    47    extract the (name,value) pair. Returns as soon as
    48    the first non-option argument was detected.
    49    """
    50
    51    while args:
    52        name, value = parse_arg(args[0])
    53        if name:
    54            args[:] = args[1:]
    55            yield name, value
    56        elif not expect_non_options:
    57            raise CommandLineError("expected option, got '%s'"%args[0])
    58        else:
    59            return
    60
    61

Generated on Thu Apr 16 16:27:15 2009 by
synopsis (version devel)