File: getoptions.py

package info (click to toggle)
synopsis 0.8.0-5
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 10,112 kB
  • ctags: 12,996
  • sloc: cpp: 34,254; ansic: 33,620; python: 10,975; sh: 7,261; xml: 6,369; makefile: 773; asm: 445
file content (56 lines) | stat: -rw-r--r-- 1,849 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# $Id: getoptions.py,v 1.1 2003/12/11 04:38:59 stefan Exp $
#
# Copyright (C) 2003 Stefan Seefeld
# All rights reserved.
# Licensed to the public under the terms of the GNU LGPL (>= 2),
# see the file COPYING for details.
#

from __future__ import generators

import sys

def parse_option(arg):
   """The required format is '--option[=[arg]]' or 'option=arg'.
   In the former case the optional argument is interpreted as
   a string (only '--option' sets the value to True, '--option='
   sets it to the empty string), in the latter case the argument
   is evaluated as a python expression.
   Returns (None, None) for non-option argument"""
   
   if arg.find('=') == -1 and not arg.startswith('--'):
      return None, None # we are done
   attribute = arg.split('=', 1)
   if len(attribute) == 2:
      name, value = attribute
      if name.startswith('--'):
         name = name[2:] # value is a string
      else:
         try:
            value = eval(value) # it's a python expression
         except:
            sys.stderr.write("""an error occured trying to evaluate the value of \'%s\' (\'%s\')
to pass this as a string, please use %s="'%s'" \n"""%(name, value, name, value))
            sys.exit(-1)
   else:
      name, value = attribute[0][2:], True # flag the attribute as 'set'

   return name, value

def get_options(args, parse_arg = parse_option):
   """provide an iterator over the options in args.
   All found options are stripped, such that args will
   contain the remainder, i.e. non-option arguments.
   Pass each argument to the parse_option function to
   extract the (name,value) pair. Returns as soon as
   the first non-option argument was detected.
   """

   while args:
      name, value = parse_arg(args[0])
      if name:
         args[:] = args[1:]
         yield name, value
      else:
         return