1 # Author: David Goodger
2 # Contact: goodger@users.sourceforge.net
5 # Copyright: This module has been placed in the public domain.
8 Command-line and common processing for Docutils front-end tools.
10 Exports the following classes:
12 * `OptionParser`: Standard Docutils command-line processing.
13 * `Option`: Customized version of `optparse.Option`; validation support.
14 * `Values`: Runtime settings; objects are simple structs
15 (``object.attribute``). Supports cumulative list settings (attributes).
16 * `ConfigParser`: Standard Docutils config file processing.
18 Also exports the following functions:
20 * Option callbacks: `store_multiple`, `read_config_file`.
21 * Setting validators: `validate_encoding`,
22 `validate_encoding_error_handler`,
23 `validate_encoding_and_error_handler`, `validate_boolean`,
24 `validate_threshold`, `validate_colon_separated_string_list`,
25 `validate_dependency_file`.
26 * `make_paths_absolute`.
29 __docformat__
= 'reStructuredText'
36 import ConfigParser
as CP
41 from optparse
import SUPPRESS_HELP
43 import optik
as optparse
44 from optik
import SUPPRESS_HELP
47 def store_multiple(option
, opt
, value
, parser
, *args
, **kwargs
):
49 Store multiple values in `parser.values`. (Option callback.)
51 Store `None` for each attribute named in `args`, and store the value for
52 each key (attribute name) in `kwargs`.
54 for attribute
in args
:
55 setattr(parser
.values
, attribute
, None)
56 for key
, value
in kwargs
.items():
57 setattr(parser
.values
, key
, value
)
59 def read_config_file(option
, opt
, value
, parser
):
61 Read a configuration file during option processing. (Option callback.)
64 new_settings
= parser
.get_config_file_settings(value
)
65 except ValueError, error
:
67 parser
.values
.update(new_settings
, parser
)
69 def validate_encoding(setting
, value
, option_parser
,
70 config_parser
=None, config_section
=None):
74 raise (LookupError('setting "%s": unknown encoding: "%s"'
76 None, sys
.exc_info()[2])
79 def validate_encoding_error_handler(setting
, value
, option_parser
,
80 config_parser
=None, config_section
=None):
82 codecs
.lookup_error(value
)
83 except AttributeError: # prior to Python 2.3
84 if value
not in ('strict', 'ignore', 'replace', 'xmlcharrefreplace'):
86 'unknown encoding error handler: "%s" (choices: '
87 '"strict", "ignore", "replace", or "xmlcharrefreplace")' % value
),
88 None, sys
.exc_info()[2])
91 'unknown encoding error handler: "%s" (choices: '
92 '"strict", "ignore", "replace", "backslashreplace", '
93 '"xmlcharrefreplace", and possibly others; see documentation for '
94 'the Python ``codecs`` module)' % value
),
95 None, sys
.exc_info()[2])
98 def validate_encoding_and_error_handler(
99 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
101 Side-effect: if an error handler is included in the value, it is inserted
102 into the appropriate place as if it was a separate setting/option.
105 encoding
, handler
= value
.split(':')
106 validate_encoding_error_handler(
107 setting
+ '_error_handler', handler
, option_parser
,
108 config_parser
, config_section
)
110 config_parser
.set(config_section
, setting
+ '_error_handler',
113 setattr(option_parser
.values
, setting
+ '_error_handler', handler
)
116 validate_encoding(setting
, encoding
, option_parser
,
117 config_parser
, config_section
)
120 def validate_boolean(setting
, value
, option_parser
,
121 config_parser
=None, config_section
=None):
122 if isinstance(value
, types
.StringType
):
124 return option_parser
.booleans
[value
.strip().lower()]
126 raise (LookupError('unknown boolean value: "%s"' % value
),
127 None, sys
.exc_info()[2])
130 def validate_nonnegative_int(setting
, value
, option_parser
,
131 config_parser
=None, config_section
=None):
134 raise ValueError('negative value; must be positive or zero')
137 def validate_threshold(setting
, value
, option_parser
,
138 config_parser
=None, config_section
=None):
143 return option_parser
.thresholds
[value
.lower()]
144 except (KeyError, AttributeError):
145 raise (LookupError('unknown threshold: %r.' % value
),
146 None, sys
.exc_info
[2])
148 def validate_colon_separated_string_list(
149 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
150 if isinstance(value
, types
.StringType
):
151 value
= value
.split(':')
154 value
.extend(last
.split(':'))
157 def validate_url_trailing_slash(
158 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
161 elif value
.endswith('/'):
166 def validate_dependency_file(
167 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
169 return docutils
.utils
.DependencyList(value
)
171 return docutils
.utils
.DependencyList(None)
173 def make_paths_absolute(pathdict
, keys
, base_path
=None):
175 Interpret filesystem path settings relative to the `base_path` given.
177 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
178 `OptionParser.relative_path_settings`.
180 if base_path
is None:
181 base_path
= os
.getcwd()
183 if pathdict
.has_key(key
):
184 value
= pathdict
[key
]
185 if isinstance(value
, types
.ListType
):
186 value
= [make_one_path_absolute(base_path
, path
)
189 value
= make_one_path_absolute(base_path
, value
)
190 pathdict
[key
] = value
192 def make_one_path_absolute(base_path
, path
):
193 return os
.path
.abspath(os
.path
.join(base_path
, path
))
196 class Values(optparse
.Values
):
199 Updates list attributes by extension rather than by replacement.
200 Works in conjunction with the `OptionParser.lists` instance attribute.
203 def __init__(self
, *args
, **kwargs
):
204 optparse
.Values
.__init
__(self
, *args
, **kwargs
)
205 if (not hasattr(self
, 'record_dependencies')
206 or self
.record_dependencies
is None):
207 # Set up dependency list, in case it is needed.
208 self
.record_dependencies
= docutils
.utils
.DependencyList()
210 def update(self
, other_dict
, option_parser
):
211 if isinstance(other_dict
, Values
):
212 other_dict
= other_dict
.__dict
__
213 other_dict
= other_dict
.copy()
214 for setting
in option_parser
.lists
.keys():
215 if (hasattr(self
, setting
) and other_dict
.has_key(setting
)):
216 value
= getattr(self
, setting
)
218 value
+= other_dict
[setting
]
219 del other_dict
[setting
]
220 self
._update
_loose
(other_dict
)
223 """Return a shallow copy of `self`."""
224 return self
.__class
__(defaults
=self
.__dict
__)
227 class Option(optparse
.Option
):
229 ATTRS
= optparse
.Option
.ATTRS
+ ['validator', 'overrides']
231 def process(self
, opt
, value
, values
, parser
):
233 Call the validator function on applicable settings and
234 evaluate the 'overrides' option.
235 Extends `optparse.Option.process`.
237 result
= optparse
.Option
.process(self
, opt
, value
, values
, parser
)
241 value
= getattr(values
, setting
)
243 new_value
= self
.validator(setting
, value
, parser
)
244 except Exception, error
:
245 raise (optparse
.OptionValueError(
246 'Error in option "%s":\n %s: %s'
247 % (opt
, error
.__class
__.__name
__, error
)),
248 None, sys
.exc_info()[2])
249 setattr(values
, setting
, new_value
)
251 setattr(values
, self
.overrides
, None)
255 class OptionParser(optparse
.OptionParser
, docutils
.SettingsSpec
):
258 Parser for command-line and library use. The `settings_spec`
259 specification here and in other Docutils components are merged to build
260 the set of command-line options and runtime settings for this process.
262 Common settings (defined below) and component-specific settings must not
263 conflict. Short options are reserved for common settings, and components
264 are restrict to using long options.
267 standard_config_files
= [
268 '/etc/docutils.conf', # system-wide
269 './docutils.conf', # project-specific
270 '~/.docutils'] # user-specific
271 """Docutils configuration files, using ConfigParser syntax. Filenames
272 will be tilde-expanded later. Later files override earlier ones."""
274 threshold_choices
= 'info 1 warning 2 error 3 severe 4 none 5'.split()
275 """Possible inputs for for --report and --halt threshold values."""
277 thresholds
= {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
278 """Lookup table for --report and --halt threshold values."""
280 booleans
={'1': 1, 'on': 1, 'yes': 1, 'true': 1,
281 '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0}
282 """Lookup table for boolean configuration file settings."""
284 if hasattr(codecs
, 'backslashreplace_errors'):
285 default_error_encoding_error_handler
= 'backslashreplace'
287 default_error_encoding_error_handler
= 'replace'
290 'General Docutils Options',
292 (('Specify the document title as metadata (not part of the document '
293 'body). Overrides a document-provided title. There is no default.',
295 ('Include a "Generated by Docutils" credit and link at the end '
297 ['--generator', '-g'], {'action': 'store_true',
298 'validator': validate_boolean
}),
299 ('Do not include a generator credit.',
300 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
301 ('Include the date at the end of the document (UTC).',
302 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
303 'dest': 'datestamp'}),
304 ('Include the time & date at the end of the document (UTC).',
305 ['--time', '-t'], {'action': 'store_const',
306 'const': '%Y-%m-%d %H:%M UTC',
307 'dest': 'datestamp'}),
308 ('Do not include a datestamp of any kind.',
309 ['--no-datestamp'], {'action': 'store_const', 'const': None,
310 'dest': 'datestamp'}),
311 ('Include a "View document source" link (relative to destination).',
312 ['--source-link', '-s'], {'action': 'store_true',
313 'validator': validate_boolean
}),
314 ('Use the supplied <URL> verbatim for a "View document source" '
315 'link; implies --source-link.',
316 ['--source-url'], {'metavar': '<URL>'}),
317 ('Do not include a "View document source" link.',
318 ['--no-source-link'],
319 {'action': 'callback', 'callback': store_multiple
,
320 'callback_args': ('source_link', 'source_url')}),
321 ('Enable backlinks from section headers to table of contents '
322 'entries. This is the default.',
323 ['--toc-entry-backlinks'],
324 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
325 'default': 'entry'}),
326 ('Enable backlinks from section headers to the top of the table of '
328 ['--toc-top-backlinks'],
329 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
330 ('Disable backlinks to the table of contents.',
331 ['--no-toc-backlinks'],
332 {'dest': 'toc_backlinks', 'action': 'store_false'}),
333 ('Enable backlinks from footnotes and citations to their '
334 'references. This is the default.',
335 ['--footnote-backlinks'],
336 {'action': 'store_true', 'default': 1,
337 'validator': validate_boolean
}),
338 ('Disable backlinks from footnotes and citations.',
339 ['--no-footnote-backlinks'],
340 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
341 ('Disable Docutils section numbering',
342 ['--no-section-numbering'],
343 {'action': 'store_false', 'dest': 'sectnum_xform',
344 'default': 1, 'validator': validate_boolean
}),
345 ('Set verbosity threshold; report system messages at or higher than '
346 '<level> (by name or number: "info" or "1", warning/2, error/3, '
347 'severe/4; also, "none" or "5"). Default is 2 (warning).',
348 ['--report', '-r'], {'choices': threshold_choices
, 'default': 2,
349 'dest': 'report_level', 'metavar': '<level>',
350 'validator': validate_threshold
}),
351 ('Report all system messages, info-level and higher. (Same as '
353 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
354 'dest': 'report_level'}),
355 ('Do not report any system messages. (Same as "--report=none".)',
356 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
357 'dest': 'report_level'}),
358 ('Set the threshold (<level>) at or above which system messages are '
359 'converted to exceptions, halting execution immediately by '
360 'exiting (or propagating the exception if --traceback set). '
361 'Levels as in --report. Default is 4 (severe).',
362 ['--halt'], {'choices': threshold_choices
, 'dest': 'halt_level',
363 'default': 4, 'metavar': '<level>',
364 'validator': validate_threshold
}),
365 ('Same as "--halt=info": halt processing at the slightest problem.',
366 ['--strict'], {'action': 'store_const', 'const': 'info',
367 'dest': 'halt_level'}),
368 ('Enable a non-zero exit status for normal exit if non-halting '
369 'system messages (at or above <level>) were generated. Levels as '
370 'in --report. Default is 5 (disabled). Exit status is the maximum '
371 'system message level plus 10 (11 for INFO, etc.).',
372 ['--exit-status'], {'choices': threshold_choices
,
373 'dest': 'exit_status_level',
374 'default': 5, 'metavar': '<level>',
375 'validator': validate_threshold
}),
376 ('Report debug-level system messages and generate diagnostic output.',
377 ['--debug'], {'action': 'store_true', 'validator': validate_boolean
}),
378 ('Do not report debug-level system messages or generate diagnostic '
380 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
381 ('Send the output of system messages (warnings) to <file>.',
382 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
383 ('Enable Python tracebacks when halt-level system messages and '
384 'other exceptions occur. Useful for debugging, and essential for '
386 ['--traceback'], {'action': 'store_true', 'default': None,
387 'validator': validate_boolean
}),
388 ('Disable Python tracebacks when errors occur; report just the error '
389 'instead. This is the default.',
390 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
391 ('Specify the encoding of input text. Default is locale-dependent. '
392 'Optionally also specify the error handler for undecodable '
393 'characters, after a colon (":"); default is "strict". (See '
394 '"--intput-encoding-error-handler".)',
395 ['--input-encoding', '-i'],
396 {'metavar': '<name[:handler]>',
397 'validator': validate_encoding_and_error_handler
}),
398 ('Specify the error handler for undecodable characters in '
399 'the input. Acceptable values include "strict", "ignore", and '
400 '"replace". Default is "strict". '
401 'Usually specified as part of --input-encoding.',
402 ['--input-encoding-error-handler'],
403 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
404 ('Specify the text encoding for output. Default is UTF-8. '
405 'Optionally also specify the error handler for unencodable '
406 'characters, after a colon (":"); default is "strict". (See '
407 '"--output-encoding-error-handler".)',
408 ['--output-encoding', '-o'],
409 {'metavar': '<name[:handler]>', 'default': 'utf-8',
410 'validator': validate_encoding_and_error_handler
}),
411 ('Specify the error handler for unencodable characters in '
412 'the output. Acceptable values include "strict", "ignore", '
413 '"replace", "xmlcharrefreplace", and '
414 '"backslashreplace" (in Python 2.3+). Default is "strict". '
415 'Usually specified as part of --output-encoding.',
416 ['--output-encoding-error-handler'],
417 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
418 ('Specify the text encoding for error output. Default is ASCII. '
419 'Optionally also specify the error handler for unencodable '
420 'characters, after a colon (":"); default is "%s". (See '
421 '"--output-encoding-error-handler".)'
422 % default_error_encoding_error_handler
,
423 ['--error-encoding', '-e'],
424 {'metavar': '<name[:handler]>', 'default': 'ascii',
425 'validator': validate_encoding_and_error_handler
}),
426 ('Specify the error handler for unencodable characters in '
427 'error output. See --output-encoding-error-handler for acceptable '
428 'values. Default is "%s". Usually specified as part of '
429 '--error-encoding.' % default_error_encoding_error_handler
,
430 ['--error-encoding-error-handler'],
431 {'default': default_error_encoding_error_handler
,
432 'validator': validate_encoding_error_handler
}),
433 ('Specify the language of input text (ISO 639 2-letter identifier).'
434 ' Default is "en" (English).',
435 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
436 'metavar': '<name>'}),
437 ('Write dependencies (caused e.g. by file inclusions) to '
438 '<file>. Useful in conjunction with programs like "make".',
439 ['--record-dependencies'],
440 {'metavar': '<file>', 'validator': validate_dependency_file
,
441 'default': None}), # default set in Values class
442 ('Read configuration settings from <file>, if it exists.',
443 ['--config'], {'metavar': '<file>', 'type': 'string',
444 'action': 'callback', 'callback': read_config_file
}),
445 ("Show this program's version number and exit.",
446 ['--version', '-V'], {'action': 'version'}),
447 ('Show this help message and exit.',
448 ['--help', '-h'], {'action': 'help'}),
449 # Typically not useful for non-programmatical use.
450 (SUPPRESS_HELP
, ['--id-prefix'], {'default': ''}),
451 (SUPPRESS_HELP
, ['--auto-id-prefix'], {'default': 'id'}),
452 # Hidden options, for development use only:
453 (SUPPRESS_HELP
, ['--dump-settings'], {'action': 'store_true'}),
454 (SUPPRESS_HELP
, ['--dump-internals'], {'action': 'store_true'}),
455 (SUPPRESS_HELP
, ['--dump-transforms'], {'action': 'store_true'}),
456 (SUPPRESS_HELP
, ['--dump-pseudo-xml'], {'action': 'store_true'}),
457 (SUPPRESS_HELP
, ['--expose-internal-attribute'],
458 {'action': 'append', 'dest': 'expose_internals',
459 'validator': validate_colon_separated_string_list
}),
460 (SUPPRESS_HELP
, ['--strict-visitor'], {'action': 'store_true'}),
462 """Runtime settings and command-line options common to all Docutils front
463 ends. Setting specs specific to individual Docutils components are also
464 used (see `populate_from_components()`)."""
466 settings_defaults
= {'_disable_config': None,
468 '_destination': None,}
469 """Defaults for settings that don't have command-line option equivalents."""
471 relative_path_settings
= ('warning_stream',)
473 config_section
= 'general'
475 version_template
= ('%%prog (Docutils %s [%s])'
476 % (docutils
.__version
__, docutils
.__version
_details
__))
477 """Default version message."""
479 def __init__(self
, components
=(), defaults
=None, read_config_files
=None,
482 `components` is a list of Docutils components each containing a
483 ``.settings_spec`` attribute. `defaults` is a mapping of setting
488 """Set of list-type settings."""
490 optparse
.OptionParser
.__init
__(
491 self
, option_class
=Option
, add_help_option
=None,
492 formatter
=optparse
.TitledHelpFormatter(width
=78),
495 self
.version
= self
.version_template
496 # Make an instance copy (it will be modified):
497 self
.relative_path_settings
= list(self
.relative_path_settings
)
498 self
.components
= (self
,) + tuple(components
)
499 self
.populate_from_components(self
.components
)
500 self
.set_defaults(**(defaults
or {}))
501 if read_config_files
and not self
.defaults
['_disable_config']:
503 config_settings
= self
.get_standard_config_settings()
504 except ValueError, error
:
506 self
.set_defaults(**config_settings
.__dict
__)
508 def populate_from_components(self
, components
):
510 For each component, first populate from the `SettingsSpec.settings_spec`
511 structure, then from the `SettingsSpec.settings_defaults` dictionary.
512 After all components have been processed, check for and populate from
513 each component's `SettingsSpec.settings_default_overrides` dictionary.
515 for component
in components
:
516 if component
is None:
518 settings_spec
= component
.settings_spec
519 self
.relative_path_settings
.extend(
520 component
.relative_path_settings
)
521 for i
in range(0, len(settings_spec
), 3):
522 title
, description
, option_spec
= settings_spec
[i
:i
+3]
524 group
= optparse
.OptionGroup(self
, title
, description
)
525 self
.add_option_group(group
)
527 group
= self
# single options
528 for (help_text
, option_strings
, kwargs
) in option_spec
:
529 option
= group
.add_option(help=help_text
, *option_strings
,
531 if kwargs
.get('action') == 'append':
532 self
.lists
[option
.dest
] = 1
533 if component
.settings_defaults
:
534 self
.defaults
.update(component
.settings_defaults
)
535 for component
in components
:
536 if component
and component
.settings_default_overrides
:
537 self
.defaults
.update(component
.settings_default_overrides
)
539 def get_standard_config_files(self
):
540 """Return list of config files, from environment or standard."""
542 config_files
= os
.environ
['DOCUTILSCONFIG'].split(os
.pathsep
)
544 config_files
= self
.standard_config_files
545 return [os
.path
.expanduser(f
) for f
in config_files
if f
.strip()]
547 def get_standard_config_settings(self
):
549 for filename
in self
.get_standard_config_files():
550 settings
.update(self
.get_config_file_settings(filename
), self
)
553 def get_config_file_settings(self
, config_file
):
554 """Returns a dictionary containing appropriate config file settings."""
555 parser
= ConfigParser()
556 parser
.read(config_file
, self
)
557 base_path
= os
.path
.dirname(config_file
)
560 for component
in self
.components
:
563 for section
in (tuple(component
.config_section_dependencies
or ())
564 + (component
.config_section
,)):
565 if applied
.has_key(section
):
568 settings
.update(parser
.get_section(section
), self
)
570 settings
.__dict
__, self
.relative_path_settings
, base_path
)
571 return settings
.__dict
__
573 def check_values(self
, values
, args
):
574 """Store positional arguments as runtime settings."""
575 values
._source
, values
._destination
= self
.check_args(args
)
576 make_paths_absolute(values
.__dict
__, self
.relative_path_settings
,
580 def check_args(self
, args
):
581 source
= destination
= None
584 if source
== '-': # means stdin
587 destination
= args
.pop(0)
588 if destination
== '-': # means stdout
591 self
.error('Maximum 2 arguments allowed.')
592 if source
and source
== destination
:
593 self
.error('Do not specify the same file for both source and '
594 'destination. It will clobber the source file.')
595 return source
, destination
597 def get_default_values(self
):
598 """Needed to get custom `Values` instances."""
599 return Values(self
.defaults
)
601 def get_option_by_dest(self
, dest
):
603 Get an option by its dest.
605 If you're supplying a dest which is shared by several options,
606 it is undefined which option of those is returned.
608 A KeyError is raised if there is no option with the supplied
611 for group
in self
.option_groups
+ [self
]:
612 for option
in group
.option_list
:
613 if option
.dest
== dest
:
615 raise KeyError('No option with dest == %r.' % dest
)
618 class ConfigParser(CP
.ConfigParser
):
621 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
622 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
623 'pep_template': ('pep_html writer', 'template')}
624 """{old setting: (new section, new setting)} mapping, used by
625 `handle_old_config`, to convert settings from the old [options] section."""
628 The "[option]" section is deprecated. Support for old-format configuration
629 files may be removed in a future Docutils release. Please revise your
630 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
631 section "Old-Format Configuration Files".
634 def read(self
, filenames
, option_parser
):
635 if type(filenames
) in (types
.StringType
, types
.UnicodeType
):
636 filenames
= [filenames
]
637 for filename
in filenames
:
638 CP
.ConfigParser
.read(self
, filename
)
639 if self
.has_section('options'):
640 self
.handle_old_config(filename
)
641 self
.validate_settings(filename
, option_parser
)
643 def handle_old_config(self
, filename
):
644 warnings
.warn_explicit(self
.old_warning
, ConfigDeprecationWarning
,
646 options
= self
.get_section('options')
647 if not self
.has_section('general'):
648 self
.add_section('general')
649 for key
, value
in options
.items():
650 if self
.old_settings
.has_key(key
):
651 section
, setting
= self
.old_settings
[key
]
652 if not self
.has_section(section
):
653 self
.add_section(section
)
657 if not self
.has_option(section
, setting
):
658 self
.set(section
, setting
, value
)
659 self
.remove_section('options')
661 def validate_settings(self
, filename
, option_parser
):
663 Call the validator function and implement overrides on all applicable
666 for section
in self
.sections():
667 for setting
in self
.options(section
):
669 option
= option_parser
.get_option_by_dest(setting
)
673 value
= self
.get(section
, setting
, raw
=1)
675 new_value
= option
.validator(
676 setting
, value
, option_parser
,
677 config_parser
=self
, config_section
=section
)
678 except Exception, error
:
680 'Error in config file "%s", section "[%s]":\n'
682 % (filename
, section
, error
.__class
__.__name
__,
683 error
, setting
, value
)), None, sys
.exc_info()[2])
684 self
.set(section
, setting
, new_value
)
686 self
.set(section
, option
.overrides
, None)
688 def optionxform(self
, optionstr
):
690 Transform '-' to '_' so the cmdline form of option names can be used.
692 return optionstr
.lower().replace('-', '_')
694 def get_section(self
, section
):
696 Return a given section as a dictionary (empty if the section
700 if self
.has_section(section
):
701 for option
in self
.options(section
):
702 section_dict
[option
] = self
.get(section
, option
, raw
=1)
706 class ConfigDeprecationWarning(DeprecationWarning):
707 """Warning for deprecated configuration file features."""