/usr/share/pyshared/mx/Misc/ConfigFile.py is in python-egenix-mxtools 3.2.1-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | """ ConfigFile -- Interface to simple template based configuration files.
The format of these files is as follows:
globalvar = 2
[ABC]
a = 1
b = abc.html
c = text with spaces
[DEF]
a = 2
b = a + 3
c = a string
Entries in square brackets indicate new subsections. Global
variables may be set prior to starting any subsection.
Empty lines and lines starting with '#' or ';' (comments) are
ignored.
Indentation is not necessary; lines can start at any column.
Entries may span multiple lines by using '\' continuations
at the line ends, e.g.
[Continuation]
a = first line\
second line
The lines are stripped of any white space before removing the
trailing '\' and concatenating them. Comment lines are removed as
well.
To parse these files, a template in form of a class including
subclasses (identifying the subsections) must be given to the
reader. This template defines which sections and attributes are
known. All others are rejected. A sample template for the above
looks like this:
from mx.Misc.ConfigFile import *
class Template(ConfigNamespace):
global = IntegerEntry()
class ABC(ConfigSection):
a = IntegerEntry('0')
b = StringEntry('default.html')
c = StringEntry()
class DEF(ConfigSection):
a = IntegerEntry('0')
b = EvalEntry('0')
c = StringEntry('default value')
The main class representing the global namespace of the ini file
must have ConfigNamespace as baseclass. It may contain any number
of ConfigSection subclasses each defining parsed attributes.
The ini file may only contain entries defined in this template.
In case an unknown section is found, the main class is looked up
for a ConfigSection subclass with name 'DefaultSection'. This
section object is then taken as template for a new section
of the given name.
The same feature is available for attributes in sections. In case
a given attribute is not found in the templates, the section's
'DefaultAttribute' attribute is deepcopied and the used as
attribute template.
Needs mxTools to be installed.
XXX Add support for long strings (including embedded control
characters and spanning multiple lines)
Copyright (c) 2000, Marc-Andre Lemburg; All Rights Reserved.
Copyright (c) 2000-2010, eGenix.com Software GmbH; All Rights Reserved.
See the documentation for further information on copyrights,
or contact the author. All Rights Reserved.
"""
import copy,re,types,exceptions,sys,os
import mx.Tools.NewBuiltins
from mx.Tools import freeze
import Namespace
### Globals
# Characters declaring comment lines
COMMENT_CHARS = ('#', ';')
# Print debug information ?
_debug = 0
### Errors
class Error(exceptions.StandardError):
pass
### Helpers
shell_var = re.compile('(?:\$([a-zA-Z0-9._]+)|\${([^}]*)})')
def expand_vars(text,locals,globals,
shell_var=shell_var):
""" Expands all variables of the form $var or ${var} using
the dictionaries locals,globals,os.environ in that order
as database.
Default value is the empty string, just like for shell
environment variables.
"""
while 1:
m = shell_var.search(text)
if not m:
break
g = m.groups()
varpath = (g[0] or g[1]).split('.')
varname = varpath[0]
# Find object with name varname
value = locals.get(varname,None)
if value is None:
value = globals.get(varname,None)
if value is None:
value = os.environ.get(varname,'')
# Now get the requested attribute
for attr in varpath[1:]:
try:
value = getattr(value,attr)
except AttributeError:
raise Error,'attribute "%s" undefined' % attr
# Reformat text by inserting value as string
l,r = m.span()
if isinstance(value,Entry):
entry = value
if entry.value is NotGiven:
entry.parse(entry.default,locals,globals)
value = entry.value
text = text[:l] + str(value) + text[r:]
return text
### Template entry fields
class Entry:
""" Converts the value to another datatype depending on the
.converters attribute.
Each of those functions is applied to the value. The first one
to not raise an exception succeeds.
"""
# Value
value = NotGiven
# Default value
default = ''
# Converters to be tried; order is important the first successful
# one wins
converters = (int,float,str)
def __init__(self,default=NotGiven):
if default is not NotGiven:
self.default = default
def parse(self,text,locals,globals):
""" Parse text according to the namespace dictionaries
locals and globals.
Sets self.value and returns the parsed value as well.
"""
text = self.pre_process(str(text),locals,globals)
for converter in self.converters:
try:
value = converter(text)
break
except:
lastexc = sys.exc_info()[1]
else:
# Reraise the last exception
raise lastexc
lastexc = None
self.value = value = self.post_process(value,locals,globals)
return value
def pre_process(self,text,locals,globals,
expand_vars=expand_vars):
""" Preprocess the text value.
Default behaviour is to strip the text and then
apply variable expansion.
"""
return expand_vars(text.strip(),locals,globals)
def post_process(self,value,locals,globals):
""" Postprocess the value after conversion has been
applied.
The default behaviour is to leave it as it is.
"""
return value
def __str__(self):
""" Return a stringified version of self.value.
The default value is parsed in case no value has yet been
set.
"""
if self.value is NotGiven:
self.parse(self.default,{},{})
return str(self.value)
###
def integer_value(value):
""" Convert value to an integer.
Takes base indicators into account, such as 0x for base-16,
0 for base-7.
"""
return int(value, 0)
class IntegerEntry(Entry):
""" Converts the value to an integer.
"""
converters = (integer_value,)
class FloatEntry(Entry):
""" Converts the value to a float.
"""
converters = (float,)
class NumericEntry(Entry):
""" Converts the value to a number (integer or float).
"""
converters = (integer_value, float)
class StringEntry(Entry):
""" Converts the value to a string.
"""
converters = (str,)
def comma_list(text,
map=map,tuple=tuple):
return [x.strip() for x in text.split(',')]
def spaced_list(text,
map=map,tuple=tuple):
return [x.strip() for x in text.split()]
class TupleEntry(Entry):
""" Converts the value to a tuple of strings.
value must be a string with entries separated by ','. Entries
are split at each occurance of ',' and then stripped of
surrounding spaces.
"""
converters = (comma_list,)
def post_process(self,value,locals,globals):
return tuple(value)
# Alias
StringTupleEntry = TupleEntry
CommaTupleEntry = TupleEntry
class ListEntry(Entry):
""" Converts the value to a list of strings.
value must be a string with entries separated by ','. Entries
are split at each occurance of ',' and then stripped of
surrounding spaces.
"""
converters = (comma_list,)
# Alias
StringListEntry = ListEntry
CommaListEntry = ListEntry
class SpacedTupleEntry(TupleEntry):
""" Converts the value to a tuple of strings.
value must be a string with entries separated by
whitespace. Entries are split at each occurance of whitespace;
surrounding spaces is removed.
"""
converters = (spaced_list,)
class SpacedListEntry(ListEntry):
""" Converts the value to a list of strings.
value must be a string with entries separated by
whitespace. Entries are split at each occurance of whitespace;
surrounding spaces is removed.
"""
converters = (spaced_list,)
class FileEntry(Entry):
""" Entry field for an OS file.
"""
converters = (str,)
class PathEntry(Entry):
""" Entry field for an OS path.
Paths will always end with os.sep if given.
"""
converters = (str,)
def post_process(self,value,locals,globals):
if value and value[-1] != os.sep:
value = value + os.sep
return value
class AbsoluteFileEntry(Entry):
""" Entry field for an absolute OS pathname.
The pathname will always start with os.sep if given.
"""
converters = (str,)
def post_process(self,value,locals,globals):
if value and value[0] != os.sep:
value = os.sep + value
return value
class AbsolutePathEntry(Entry):
""" Entry field for an absolute OS path.
The pathname will always start and end with os.sep if given.
"""
converters = (str,)
def post_process(self,value,locals,globals):
if value:
if value[0] != os.sep:
value = os.sep + value
if value[-1] != os.sep:
value = value + os.sep
return value
class RelativePathEntry(PathEntry):
""" Entry field for relative paths.
The path stored is the result of joining the given parameter
with a basepath. basepath is subject to variable expansion at
parsing time.
"""
def __init__(self,basepath,default=NotGiven):
self.basepath = basepath
PathEntry.__init__(self,default)
def post_process(self,value,locals,globals):
return os.path.join(expand_vars(self.basepath,locals,globals),value)
class RelativeFileEntry(FileEntry):
""" Entry field for relative pathnames to files.
The path stored is the result of joining the given parameter
with a basepath. basepath is subject to variable expansion at
parsing time.
"""
def __init__(self,basepath,default=NotGiven):
self.basepath = basepath
PathEntry.__init__(self,default)
def post_process(self,value,locals,globals):
return os.path.join(expand_vars(self.basepath,locals,globals),value)
class ExistingPathEntry(PathEntry):
""" Checks value to point to an existing OS path.
Raises an exception if the path does not exist.
"""
def post_process(self,value,locals,globals):
if value and value[-1] != os.sep:
value = value + os.sep
if not os.path.exists(value):
raise Error,'non existing path "%s"' % value
return value
class ExistingFileEntry(FileEntry):
""" Checks value to point to an existing file.
Raises an exception if the file does not exist.
"""
def post_process(self,value,locals,globals):
if not value or not os.path.exists(value):
raise Error,'non existing file "%s"' % value
return value
class ExistingRelativePathEntry(RelativePathEntry):
""" Entry field for relative paths.
The path stored is the result of joining the given parameter
with a basepath. Raises an exception if the path does not
exist.
"""
def post_process(self,value,locals,globals):
value = os.path.join(expand_vars(self.basepath,locals,globals),value)
if not os.path.exists(value):
raise Error,'non existing path "%s"' % value
return value
class URLEntry(StringEntry):
""" Entry field for URLs.
The field takes a default value as argument.
Needs mxHTMLTools to be installed.
"""
def post_process(self,value,locals,globals):
from mx import HTMLTools
return HTMLTools.URL(value)
class RelativeURLEntry(URLEntry):
""" Entry field for relative URLs.
A base URL can be set which is then urljoined with the
value given. The field also takes a default value.
Needs mxHTMLTools to be installed.
"""
def __init__(self,baseurl='',default=NotGiven):
self.baseurl = baseurl
StringEntry.__init__(self,default)
def post_process(self,value,locals,globals):
from mx import HTMLTools
return HTMLTools.urljoin(expand_vars(self.baseurl,locals,globals),
value)
class AbsoluteURLEntry(RelativeURLEntry):
""" Entry field for absolute URLs.
A base URL can be set which is then urljoined with the
value given. The field also takes a default value as second
argument.
"""
def post_process(self,value,locals,globals):
url = RelativeURLEntry.post_process(self,value,locals,globals)
if not url.absolute:
raise Error,'need an absolute URL: "%s"' % url
return url
class DateEntry(Entry):
""" Date entry field.
The value is stored using a DateTime instance. A time part is
ignored.
Needs mxDateTime to be installed.
"""
def post_process(self,value,locals,globals):
from mx.DateTime.Parser import DateFromString
return DateFromString(value)
class DateTimeEntry(Entry):
""" Date/time entry field.
The value is stored using a DateTime instance.
Needs mxDateTime to be installed.
"""
def post_process(self,value,locals,globals):
from mx.DateTime.Parser import DateTimeFromString
return DateTimeFromString(value)
class TimeEntry(Entry):
""" Time entry field.
The value is stored using a DateTimeDelta instance. A date
part is ignored.
Needs mxDateTime to be installed.
"""
def post_process(self,value,locals,globals):
from mx.DateTime.Parser import TimeFromString
return TimeFromString(value)
class DateTimeDeltaEntry(Entry):
""" Date/time delta entry field.
The value is stored using a DateTimeDelta instance.
Needs mxDateTime to be installed.
"""
def post_process(self,value,locals,globals):
from mx.DateTime.Parser import DateTimeDeltaFromString
return DateTimeDeltaFromString(value)
class RelativeDateTimeEntry(Entry):
""" Relative date/time entry field.
The value is stored using a RelativeDateTime instance.
Needs mxDateTime to be installed.
"""
def post_process(self,value,locals,globals):
from mx.DateTime.Parser import RelativeDateTimeFromString
return RelativeDateTimeFromString(value)
class EvalEntry(Entry):
""" Allows simple calculations to be done using the
current locals (the symbols defined in the class
where the entry is located) and globals.
"""
def parse(self,text,locals,globals,
eval=eval):
self.value = eval(text,locals,globals)
return self.value
class SafeEvalEntry(Entry):
""" Allows simple calculations to be done using the
current locals (the symbols defined in the class
where the entry is located) and globals.
Builtins are not available.
"""
def parse(self,text,locals,globals,
reval=reval):
self.value = reval(text,locals,globals)
return self.value
class DictEntry(Entry):
""" Allows the construction of a Python dictionary.
The entries value is taken as list of key: value pairs which
are evaluated in the current locals (the symbols defined in
the class where the entry is located) and globals.
Parsing is left to the Python interpreter. The needed curly
brackets {} are added by the parsing method.
Sample:
dict = 'a': (1,2,3), 'b': (3,4,5)
"""
def parse(self,text,locals,globals):
self.value = eval('{' + text + '}',locals,globals)
return self.value
### Namespace containers
class ConfigNamespace(Namespace.Namespace):
# This attribute may be set to allow new sections to be
# created by the ini-file editor. The parser will use this
# class to instantiate those sections.
DefaultSection = None
# This attribute may be set to allow new attributes to be
# created by the ini-file editor. The parser will use this
# object as template for the new attributes by deepcopying
# it.
DefaultAttribute = None
def __init__(self,
getattr=getattr,
skip_types=(types.ModuleType,
types.IntType,
types.StringType,
types.NoneType,
),
del_types=(types.FunctionType,
types.MethodType,
types.BuiltinFunctionType,
types.BuiltinMethodType,),
deepcopy=copy.deepcopy,ClassType=types.ClassType):
# Localize class attributes in the instance dict
classobj = self.__class__
freeze(classobj)
dict = self.__dict__
dict.update(classobj.__dict__)
# Fixup attributes
for name,obj in dict.items():
if name[:1] == '_ ':
# Delete all special attributes
del dict[name]
objtype = type(obj)
if objtype is ClassType:
# Handle classes
if name != 'DefaultSection' and \
issubclass(obj,ConfigSection):
# Instantiate ConfigSections
dict[name] = obj()
# leave all others as classes
elif objtype in del_types:
# Delete these types
del dict[name]
elif objtype in skip_types:
# Skip these types
pass
else:
# Deepcopy everything else
try:
dict[name] = deepcopy(obj)
except copy.error,why:
raise Error,\
'namespace entry "%s" could not be copied: %s' % \
(name,why)
#
# Dictionary like interface (we hide the internally used attributes)
#
def _items(self):
items = []
append = items.append
for k,v in self.__dict__.items():
if k[:1] == '_' or \
k in ('DefaultSection', 'DefaultAttribute', 'baseobj'):
continue
append((k,v))
return items
def _keys(self):
items = []
append = items.append
for k,v in self.__dict__.items():
if k[:1] == '_' or \
k in ('DefaultSection', 'DefaultAttribute', 'baseobj'):
continue
append(k)
return items
def _values(self):
items = []
append = items.append
for k,v in self.__dict__.items():
if k[:1] == '_' or \
k in ('DefaultSection', 'DefaultAttribute', 'baseobj'):
continue
append(v)
return items
def _dictionary(self):
d = {}
d.update(self.__dict__)
# Remove internal attributes
for k in d.keys():
if k[:1] == '_' or \
k in ('DefaultSection', 'DefaultAttribute', 'baseobj'):
del d[k]
return d
class ConfigSection(ConfigNamespace):
pass
###
parse_section = re.compile('\[([a-zA-Z_][a-zA-Z_0-9]*)\]')
parse_setattr = re.compile('([a-zA-Z_][a-zA-Z_0-9]*)[ \t]*=[ \t]*(.*)')
class ConfigFile:
""" Configuration file reader.
Takes a template (a ConfigNamespace subclass) as input which
defines sections using classes. Sections may include instances
of Entry as attributes. These are then used to process the
file input.
The template is (deep-)copied and placed into the instance
variable .data (a ConfigNamespace instance) prior to reading
the file. Section classes are replaced with ConfigSection
instances.
After successful reading the file, the configuration
information is available through this variable.
Errors are indicated by exceptions of type Error. These always
have values (line_number, explanation) where line_number is 0
for errors which do not refer to one specific line in the
file.
"""
data = None # configuration namespace
def __init__(self,template):
self.template = template
self.reset()
def reset(self,
deepcopy=copy.deepcopy,ClassType=types.ClassType,
ModuleType=types.ModuleType):
""" Reset the object to its initial state.
This initializes self.data to a template instance.
"""
self.data = self.template()
def read(self,file,
deepcopy=copy.deepcopy):
""" Read and parse the open file.
The configuration is stored in the instance variable
.data.
"""
context = {}
sectionname = ''
data = self.data # Configuration object
section = data # Current section object
globals = data.__dict__ # Global namespace
locals = globals # Local namespace
lineno = 0
if _debug:
print 'Reading config file:'
while 1:
line = file.readline()
lineno = lineno + 1
if not line:
break
line = line.strip()
if not line or line[0] in COMMENT_CHARS:
# Comment or emtpy line: ignore
continue
if _debug:
print ' read %s' % repr(line)
# Continuation
current_lineno = lineno
while line[-1] == '\\':
nextline = file.readline()
lineno = lineno + 1
if not nextline:
# EOF: end of continuation
line = line[:-1]
break
nextline = nextline.strip()
if not nextline:
# Empty line: end of continuation
line = line[:-1]
break
if nextline[0] == '#':
# Comment: ignore
continue
if _debug:
print ' read continuation %s' % repr(nextline)
# Add nextline to line
line = line[:-1] + nextline
if _debug:
print ' processing %s' % repr(line)
m = parse_section.match(line)
if m:
# Start a new section
sectionname = m.groups()[0]
section = getattr(data,sectionname,None)
if section is None:
if data.DefaultSection:
# Instantiate default section for use as
# section object and register in data
section = data.DefaultSection()
setattr(data,sectionname,section)
else:
raise Error,(current_lineno,
'unknown section "%s"' %
sectionname)
#print 'Switched to section:',sectionname
locals = section.__dict__
continue
m = parse_setattr.match(line)
if m:
# Add a new attribute
name,value = m.groups()
entry = locals.get(name,None)
if sectionname:
attrname = sectionname + '.' + name
else:
attrname = name
if entry is None:
if section.DefaultAttribute:
# Instantiate default attribute for use as
# attribute object and register in section
entry = deepcopy(section.DefaultAttribute)
setattr(section,name,entry)
else:
raise Error,(current_lineno,
'unknown attribute: "%s"' % attrname)
if not isinstance(entry, Entry):
# Since we replace the parsed entries with their parsed
# value any occurance of non-Entry instances point
# to a duplicate definition of an entry
raise Error,(current_lineno,
'duplicate attribute definition for "%s"' %
attrname)
try:
entry.parse(value,locals,globals)
except:
raise Error,(current_lineno,
'invalid attribute value for "%s" (%s: %s)' %
(attrname,
sys.exc_info()[0],sys.exc_info()[1]))
# Replace with parsed value
locals[name] = entry.value
continue
# The line doesn't have a valid syntax: ignore it
if _debug:
print 'Ignoring invalid config file line %i: %s' % \
(current_lineno,
repr(line))
# Check for missing entries and replace with parsed values
for name,obj in globals.items():
if isinstance(obj,Entry):
if obj.value is not NotGiven:
globals[name] = obj.value
else:
try:
obj.parse(obj.default,locals,globals)
globals[name] = obj.value
except:
raise Error,\
(0,
'invalid default attribute '
'value for global "%s" (%s)' %
(name,str(sys.exc_info()[1])))
elif isinstance(obj,ConfigSection):
locals = obj.__dict__
sectionname = name
for name,obj in locals.items():
if isinstance(obj,Entry):
if obj.value is not NotGiven:
locals[name] = obj.value
else:
try:
obj.parse(obj.default,locals,globals)
locals[name] = obj.value
except:
import traceback; traceback.print_exc()
raise Error,\
(0,
'invalid default attribute '
'value for local "%s" (%s)' %
(name,str(sys.exc_info()[1])))
### Test
if __name__ == '__main__':
class Template(ConfigNamespace):
import sys
globalvar = IntegerEntry(1)
# New attributes in the global section are strings
DefaultAttribute = StringEntry('')
class ABC(ConfigSection):
a = IntegerEntry('0')
b = StringEntry('default.html')
c = StringEntry()
d = StringTupleEntry('a,b')
path = ExistingPathEntry('.')
# Use this as template for new attributes
DefaultAttribute = RelativePathEntry('..','')
class DEF(ConfigSection):
a = IntegerEntry('0')
b = EvalEntry('0')
c = StringEntry('default value')
d = RelativePathEntry('$ABC.b','HOME')
g = IntegerEntry('0')
continuation = CommaTupleEntry('')
databases = DictEntry('')
timeout = TimeEntry('0:15:00.23')
# Default section
DefaultSection = ABC
text = """\
# Luckily we don't have to pay attention to proper indentation
# or whether strings have quotes or not... the template knows
# what to do.
globalvar = 2
# New global attribute
test = text
[ABC]
a = 1
b = abc.html
c = text with spaces
d = heinz, kunz, philipp
path = /tmp
# A new attribute
new = .cshrc
[DEF]
a = 2
b = a + 3
c = $PWD
d = home
continuation = first line, \\
# Comment should not hurt
second line, \\
# Invalid syntax:
third line \\
databases = 'iODBC': (sys,sys.exit,('c',1,2)), \\
'Adabas': (sys,sys.exit,('x','y','z'))
[NewSection]
a = 3
"""
import cStringIO
f = cStringIO.StringIO(text)
cf = ConfigFile(Template)
cf.read(f)
|