本文整理汇总了Python中coalib.parsing.ConfParser.ConfParser类的典型用法代码示例。如果您正苦于以下问题:Python ConfParser类的具体用法?Python ConfParser怎么用?Python ConfParser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConfParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
def load(cls, language: str, docstyle: str, coalang_dir=None):
"""
Loads a ``DocstyleDefinition`` from the coala docstyle definition files.
This function considers all settings inside the according coalang-files
as markers.
:param language: The case insensitive programming language of
the documentation comment as a string.
:param docstyle: The case insensitive documentation
style/tool used to document code, e.g.
``"default"`` or ``"doxygen"``.
:param coalang_dir: Path to directory with coalang docstyle
definition files. This replaces the default
path if given.
:raises FileNotFoundError: Raised when the given docstyle was not
found.
:raises KeyError: Raised when the given language is not
defined for given docstyle.
:return: The ``DocstyleDefinition`` for given language
and docstyle.
"""
docstyle = docstyle.lower()
language_config_parser = ConfParser(remove_empty_iter_elements=False)
coalang_file = os.path.join(
coalang_dir or os.path.dirname(__file__), docstyle + ".coalang")
try:
docstyle_settings = language_config_parser.parse(coalang_file)
except FileNotFoundError:
raise FileNotFoundError("Docstyle definition " + repr(docstyle) +
" not found.")
language = language.lower()
try:
docstyle_settings = docstyle_settings[language]
except KeyError:
raise KeyError("Language {!r} is not defined for docstyle {!r}."
.format(language, docstyle))
marker_sets = (tuple(value)
for key, value in
filter(lambda kv: not kv[0].startswith("comment"),
docstyle_settings.contents.items()))
return cls(language, docstyle, marker_sets)
示例2: get_available_definitions
def get_available_definitions():
"""
Returns a sequence of pairs with ``(docstyle, language)`` which are
available when using ``load()``.
:return: A sequence of pairs with ``(docstyle, language)``.
"""
language_config_parser = ConfParser(remove_empty_iter_elements=False)
pattern = os.path.join(os.path.dirname(__file__), '*.coalang')
for coalang_file in iglob(pattern):
docstyle = os.path.splitext(os.path.basename(coalang_file))[0]
# Ignore files that are not lowercase, as coalang files have to be.
if docstyle.lower() == docstyle:
for language in language_config_parser.parse(coalang_file):
yield docstyle, language.lower()
示例3: setUp
def setUp(self):
self.file = os.path.join(tempfile.gettempdir(), "ConfParserTestFile")
with open(self.file, "w", encoding="utf-8") as file:
file.write(self.example_file)
self.conf_parser = ConfParser()
self.write_file_name = os.path.join(tempfile.gettempdir(), "ConfWriterTestFile")
self.uut = ConfWriter(self.write_file_name)
示例4: setUp
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, ".coafile")
self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
with open(self.file, "w") as filehandler:
filehandler.write(self.example_file)
self.uut = ConfParser()
try:
os.remove(self.nonexistentfile)
except FileNotFoundError:
pass
示例5: ConfWriterTest
class ConfWriterTest(unittest.TestCase):
example_file = ("to be ignored \n"
" save=true\n"
" a_default, another = val \n"
" TEST = tobeignored # thats a comment \n"
" test = push \n"
" t = \n"
" [MakeFiles] \n"
" j , ANother = a \n"
" multiline \n"
" value \n"
" ; just a omment \n"
" ; just a omment \n")
def setUp(self):
self.file = os.path.join(tempfile.gettempdir(), "ConfParserTestFile")
with open(self.file, "w", encoding='utf-8') as filehandler:
filehandler.write(self.example_file)
self.conf_parser = ConfParser()
self.write_file_name = os.path.join(tempfile.gettempdir(),
"ConfWriterTestFile")
self.uut = ConfWriter(self.write_file_name)
def tearDown(self):
self.uut.close()
os.remove(self.file)
os.remove(self.write_file_name)
def test_exceptions(self):
self.assertRaises(TypeError, self.uut.write_section, 5)
def test_write(self):
result_file = ["[Default]\n",
"save = true\n",
"a_default, another = val\n",
"# thats a comment\n",
"test = push\n",
"t = \n",
"\n",
"[MakeFiles]\n",
"j, ANother = a\n",
"multiline\n",
"value\n",
"; just a omment\n",
"; just a omment\n"]
self.uut.write_sections(self.conf_parser.parse(self.file))
self.uut.close()
with open(self.write_file_name, "r") as f:
lines = f.readlines()
self.assertEqual(result_file, lines)
示例6: setUp
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, '.coafile')
self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t')
with open(self.file, 'w') as file:
file.write(self.example_file)
self.uut = ConfParser()
try:
os.remove(self.nonexistentfile)
except FileNotFoundError:
pass
self.sections = self.uut.parse(self.file)
示例7: __init__
def __init__(self):
self.cli_sections = None
self.default_sections = None
self.user_sections = None
self.coafile_sections = None
self.sections = None
self.cli_parser = CliParser()
self.conf_parser = ConfParser()
self.conf_writer = None
self.local_bears = {}
self.global_bears = {}
self.targets = []
示例8: setUp
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, ".coafile")
self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
with open(self.file, "w") as filehandler:
filehandler.write(self.example_file)
self.uut = ConfParser()
if sys.version_info < (3, 3):
err = OSError
else:
err = FileNotFoundError
try:
os.remove(self.nonexistentfile)
except err:
pass
示例9: ConfParserTest
class ConfParserTest(unittest.TestCase):
example_file = """to be ignored
a_default, another = val
TEST = tobeignored # do you know that thats a comment
test = push
t =
escaped_\\=equal = escaped_\\#hash
escaped_\\\\backslash = escaped_\\ space
escaped_\\,comma = escaped_\\.dot
[MakeFiles]
j , another = a
multiline
value
# just a omment
# just a omment
nokey. = value
default.test = content
makefiles.lastone = val
[EMPTY_ELEM_STRIP]
A = a, b, c
B = a, ,, d
C = ,,,
"""
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, '.coafile')
self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t')
with open(self.file, 'w') as file:
file.write(self.example_file)
self.uut = ConfParser()
try:
os.remove(self.nonexistentfile)
except FileNotFoundError:
pass
self.sections = self.uut.parse(self.file)
def tearDown(self):
os.remove(self.file)
def test_parse_nonexisting_file(self):
self.assertRaises(FileNotFoundError,
self.uut.parse,
self.nonexistentfile)
self.assertNotEqual(self.uut.parse(self.file, True), self.sections)
def test_parse_nonexisting_section(self):
self.assertRaises(IndexError,
self.uut.get_section,
'inexistent section')
def test_parse_default_section(self):
default_should = OrderedDict([
('a_default', 'val'),
('another', 'val'),
('comment0', '# do you know that thats a comment'),
('test', 'content'),
('t', ''),
('escaped_=equal', 'escaped_#hash'),
('escaped_\\backslash', 'escaped_ space'),
('escaped_,comma', 'escaped_.dot')])
key, val = self.sections.popitem(last=False)
self.assertTrue(isinstance(val, Section))
self.assertEqual(key, 'default')
is_dict = OrderedDict()
for k in val:
is_dict[k] = str(val[k])
self.assertEqual(is_dict, default_should)
def test_parse_makefiles_section(self):
makefiles_should = OrderedDict([
('j', 'a\nmultiline\nvalue'),
('another', 'a\nmultiline\nvalue'),
('comment1', '# just a omment'),
('comment2', '# just a omment'),
('lastone', 'val'),
('comment3', ''),
('a_default', 'val'),
('comment0', '# do you know that thats a comment'),
('test', 'content'),
('t', ''),
('escaped_=equal', 'escaped_#hash'),
('escaped_\\backslash', 'escaped_ space'),
('escaped_,comma', 'escaped_.dot')])
# Pop off the default section.
self.sections.popitem(last=False)
key, val = self.sections.popitem(last=False)
self.assertTrue(isinstance(val, Section))
self.assertEqual(key, 'makefiles')
is_dict = OrderedDict()
for k in val:
is_dict[k] = str(val[k])
#.........这里部分代码省略.........
示例10: test_remove_empty_iter_elements
def test_remove_empty_iter_elements(self):
# Test with empty-elem stripping.
uut = ConfParser(remove_empty_iter_elements=True)
uut.parse(self.file)
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']),
['a', 'b', 'c'])
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']),
['a', 'd'])
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']),
[])
# Test without stripping.
uut = ConfParser(remove_empty_iter_elements=False)
uut.parse(self.file)
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']),
['a', 'b', 'c'])
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']),
['a', '', '', 'd'])
self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']),
['', '', '', ''])
示例11: run
class SectionManager:
"""
The SectionManager does the following things:
- Reading all settings in sections from
- Default config
- CLI
- Configuration file
- Collecting all the bears
- Filling up all needed settings
- Write back the new sections to the configuration file if needed
- Give all information back to caller
This is done when the run() method is invoked. Anything else is just helper
stuff and initialization.
"""
def __init__(self):
self.cli_sections = None
self.default_sections = None
self.user_sections = None
self.coafile_sections = None
self.sections = None
self.cli_parser = CliParser()
self.conf_parser = ConfParser()
self.conf_writer = None
self.local_bears = {}
self.global_bears = {}
self.targets = []
def run(self, arg_list=sys.argv[1:]):
self._load_configuration(arg_list)
self._fill_settings()
self._save_configuration()
self._warn_nonexistent_targets()
return self.sections, self.local_bears, self.global_bears, self.targets
def _load_configuration(self, arg_list):
self.cli_sections = self.cli_parser.reparse(arg_list=arg_list)
# We dont want to store targets argument back to file, thus remove it
for item in list(
self.cli_sections["default"].contents.pop("targets", "")):
self.targets.append(item.lower())
self.default_sections = self._load_config_file(
StringConstants.system_coafile)
self.user_sections = self._load_config_file(
StringConstants.user_coafile,
silent=True)
default_config = str(
self.default_sections["default"].get("config", ".coafile"))
user_config = str(
self.user_sections["default"].get("config", default_config))
config = os.path.abspath(str(
self.cli_sections["default"].get("config", user_config)))
self.coafile_sections = self._load_config_file(config)
self.sections = self._merge_section_dicts(self.default_sections,
self.user_sections)
self.sections = self._merge_section_dicts(self.sections,
self.coafile_sections)
self.sections = self._merge_section_dicts(self.sections,
self.cli_sections)
for section in self.sections:
if section != "default":
self.sections[section].defaults = self.sections["default"]
def _load_config_file(self, filename, silent=False):
"""
Loads sections from a config file. Prints an appropriate warning if
it doesn't exist and returns a section dict containing an empty
default section in that case.
It assumes that the cli_sections are available.
:param filename: The file to load settings from.
:param silent: Whether or not to warn the user if the file doesn't
exist.
"""
filename = os.path.abspath(filename)
try:
return self.conf_parser.reparse(filename)
except self.conf_parser.FileNotFoundError:
if not silent:
self.cli_sections["default"].retrieve_logging_objects()
self.cli_sections["default"].log_printer.warn(
_("The requested coafile '{filename}' does not exist. "
"Thus it will not be used.").format(filename=filename))
return {"default": Section("default")}
#.........这里部分代码省略.........
示例12: load
def load(cls, language: str, docstyle: str, coalang_dir=None):
"""
Loads a ``DocstyleDefinition`` from the coala docstyle definition files.
This function considers all settings inside the according coalang-files
as markers, except ``param_start``, ``param_end`` and ``return_sep``
which are considered as special metadata markers.
.. note::
When placing new coala docstyle definition files, these must
consist of only lowercase letters and end with ``.coalang``!
:param language: The case insensitive programming language of
the documentation comment as a string.
:param docstyle: The case insensitive documentation
style/tool used to document code, e.g.
``"default"`` or ``"doxygen"``.
:param coalang_dir: Path to directory with coalang docstyle
definition files. This replaces the default
path if given.
:raises FileNotFoundError: Raised when the given docstyle was not
found.
:raises KeyError: Raised when the given language is not
defined for given docstyle.
:return: The ``DocstyleDefinition`` for given language
and docstyle.
"""
docstyle = docstyle.lower()
language_config_parser = ConfParser(remove_empty_iter_elements=False)
coalang_file = os.path.join(
coalang_dir or os.path.dirname(__file__), docstyle + '.coalang')
try:
docstyle_settings = language_config_parser.parse(coalang_file)
except FileNotFoundError:
raise FileNotFoundError('Docstyle definition ' + repr(docstyle) +
' not found.')
language = language.lower()
try:
docstyle_settings = docstyle_settings[language]
except KeyError:
raise KeyError('Language {!r} is not defined for docstyle {!r}.'
.format(language, docstyle))
metadata_settings = ('param_start', 'param_end', 'return_sep')
metadata = cls.Metadata(*(str(docstyle_settings.get(req_setting, ''))
for req_setting in metadata_settings))
marker_sets = (tuple(value)
for key, value in
docstyle_settings.contents.items()
if key not in metadata_settings and
not key.startswith('comment'))
return cls(language, docstyle, marker_sets, metadata)
示例13: ConfParserTest
class ConfParserTest(unittest.TestCase):
example_file = """to be ignored
a_default, another = val
TEST = tobeignored # do you know that thats a comment
test = push
t =
[MakeFiles]
j , another = a
multiline
value
# just a omment
# just a omment
nokey. = value
default.test = content
makefiles.lastone = val
[EMPTY_ELEM_STRIP]
A = a, b, c
B = a, ,, d
C = ,,,
"""
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, ".coafile")
self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
with open(self.file, "w") as filehandler:
filehandler.write(self.example_file)
self.uut = ConfParser()
try:
os.remove(self.nonexistentfile)
except FileNotFoundError:
pass
self.sections = self.uut.parse(self.file)
def tearDown(self):
os.remove(self.file)
def test_parse_nonexisting_file(self):
self.assertRaises(FileNotFoundError,
self.uut.parse,
self.nonexistentfile)
self.assertNotEqual(self.uut.parse(self.file, True), self.sections)
def test_parse_nonexisting_section(self):
self.assertRaises(IndexError,
self.uut.get_section,
"inexistent section")
def test_parse_default_section(self):
default_should = OrderedDict([
('a_default', 'val'),
('another', 'val'),
('comment0', '# do you know that thats a comment'),
('test', 'content'),
('t', '')])
key, val = self.sections.popitem(last=False)
self.assertTrue(isinstance(val, Section))
self.assertEqual(key, 'default')
is_dict = OrderedDict()
for k in val:
is_dict[k] = str(val[k])
self.assertEqual(is_dict, default_should)
def test_parse_makefiles_section(self):
makefiles_should = OrderedDict([
('j', 'a\nmultiline\nvalue'),
('another', 'a\nmultiline\nvalue'),
('comment1', '# just a omment'),
('comment2', '# just a omment'),
('lastone', 'val'),
('comment3', ''),
('a_default', 'val'),
('comment0', '# do you know that thats a comment'),
('test', 'content'),
('t', '')])
# Pop off the default section.
self.sections.popitem(last=False)
key, val = self.sections.popitem(last=False)
self.assertTrue(isinstance(val, Section))
self.assertEqual(key, 'makefiles')
is_dict = OrderedDict()
for k in val:
is_dict[k] = str(val[k])
self.assertEqual(is_dict, makefiles_should)
self.assertEqual(val["comment1"].key, "comment1")
def test_parse_empty_elem_strip_section(self):
empty_elem_strip_should = OrderedDict([
('a', 'a, b, c'),
('b', 'a, ,, d'),
('c', ',,,'),
#.........这里部分代码省略.........
示例14: ConfParserTest
class ConfParserTest(unittest.TestCase):
example_file = """setting = without_section
[foo]
to be ignored
a_default, another = val
TEST = tobeignored # do you know that thats a comment
test = push
t =
escaped_\\=equal = escaped_\\#hash
escaped_\\\\backslash = escaped_\\ space
escaped_\\,comma = escaped_\\.dot
[MakeFiles]
j , another = a
multiline
value
# just a comment
# just a comment
nokey. = value
foo.test = content
makefiles.lastone = val
append += key
[EMPTY_ELEM_STRIP]
A = a, b, c
B = a, ,, d
C = ,,,
[name]
key1 = value1
key2 = value1
key1 = value2
"""
def setUp(self):
self.tempdir = tempfile.gettempdir()
self.file = os.path.join(self.tempdir, '.coafile')
self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t')
with open(self.file, 'w') as file:
file.write(self.example_file)
self.uut = ConfParser()
try:
os.remove(self.nonexistentfile)
except FileNotFoundError:
pass
logger = logging.getLogger()
with self.assertLogs(logger, 'WARNING') as self.cm:
self.sections = self.uut.parse(self.file)
def tearDown(self):
os.remove(self.file)
def test_warning_typo(self):
logger = logging.getLogger()
with self.assertLogs(logger, 'WARNING') as cm:
newConf = ConfParser(comment_seperators=('#',))
self.assertEquals(cm.output[0], 'WARNING:root:The setting '
'`comment_seperators` is deprecated. '
'Please use `comment_separators` '
'instead.')
def test_parse_nonexisting_file(self):
self.assertRaises(FileNotFoundError,
self.uut.parse,
self.nonexistentfile)
self.assertNotEqual(self.uut.parse(self.file, True), self.sections)
def test_parse_nonexisting_section(self):
self.assertRaises(IndexError,
self.uut.get_section,
'non-existent section')
def test_parse_default_section_deprecated(self):
default_should = OrderedDict([
('setting', 'without_section')])
key, val = self.sections.popitem(last=False)
self.assertTrue(isinstance(val, Section))
self.assertEqual(key, 'default')
is_dict = OrderedDict()
for k in val:
is_dict[k] = str(val[k])
self.assertEqual(is_dict, default_should)
self.assertRegex(self.cm.output[0],
'A setting does not have a section.')
# Check if line number is correctly set when
# no section is given
line_num = val.contents['setting'].line_number
self.assertEqual(line_num, 1)
def test_parse_foo_section(self):
foo_should = OrderedDict([
('a_default', 'val'),
('another', 'val'),
('comment0', '# do you know that thats a comment'),
#.........这里部分代码省略.........
示例15: test_remove_empty_iter_elements
def test_remove_empty_iter_elements(self):
# Test with empty-elem stripping.
uut = ConfParser(remove_empty_iter_elements=True)
uut.parse(self.file)
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]),
["a", "b", "c"])
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]),
["a", "d"])
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]),
[])
# Test without stripping.
uut = ConfParser(remove_empty_iter_elements=False)
uut.parse(self.file)
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]),
["a", "b", "c"])
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]),
["a", "", "", "d"])
self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]),
["", "", "", ""])