本文整理汇总了Python中ConfigParser.MissingSectionHeaderError方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.MissingSectionHeaderError方法的具体用法?Python ConfigParser.MissingSectionHeaderError怎么用?Python ConfigParser.MissingSectionHeaderError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.MissingSectionHeaderError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_system_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def read_system_config(path=SYSTEM_CONFIG_PATH):
"""Parse and return the system config settings in /etc/encompass.conf."""
result = {}
if os.path.exists(path):
try:
import ConfigParser
except ImportError:
print "cannot parse encompass.conf. please install ConfigParser"
return
p = ConfigParser.ConfigParser()
try:
p.read(path)
for k, v in p.items('client'):
result[k] = v
except (ConfigParser.NoSectionError, ConfigParser.MissingSectionHeaderError):
pass
return result
示例2: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def __init__(self, *args, **kwargs):
"""
files: filepaths or open file objects
"""
self.files = kwargs.pop("files")
configparser.ConfigParser.__init__(self, *args, **kwargs)
for fd in self.files:
try:
self.read_file(fd)
except AttributeError:
# python 2
try:
self.readfp(fd)
except AttributeError:
self.read(fd)
except configparser.MissingSectionHeaderError:
self.read(fd)
self.auth_settings = self.get_section("auth")
self.private_cloud_settings = self.get_section("private_cloud")
示例3: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def __init__(self, config_file):
if sys.version[0] == "2":
CP.__init__(self)
else:
super().__init__()
if not os.path.exists(config_file):
raise Exception("Could not find " + config_file)
f = open(config_file)
id_string = f.readline().split("=")
if id_string[0].strip().upper() in ["CAPI", "SAPI"]:
self.type = id_string[0]
else:
raise SyntaxError("Could not find API type in " + config_file)
try:
self.version = int(id_string[1].strip())
except ValueError:
raise SyntaxError("Unknown version '{}'".format(id_string[1].strip()))
except IndexError:
raise SyntaxError("Could not find API version in " + config_file)
if sys.version[0] == "2":
exceptions = (configparser.ParsingError, configparser.DuplicateSectionError)
else:
exceptions = (
configparser.ParsingError,
configparser.DuplicateSectionError,
configparser.DuplicateOptionError,
)
try:
if sys.version[0] == "2":
self.readfp(f)
else:
self.read_file(f)
except configparser.MissingSectionHeaderError:
raise SyntaxError("Missing section header")
except exceptions as e:
raise SyntaxError(e.message)
示例4: test_parse_errors
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def test_parse_errors(self):
self.newconfig()
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n extra-spaces: splat\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n extra-spaces= splat\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n:value-without-option-name\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n=value-without-option-name\n")
self.parse_error(ConfigParser.MissingSectionHeaderError,
"No Section!\n")
示例5: test_missingsectionheadererror
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def test_missingsectionheadererror(self):
import pickle
e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line')
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
pickled = pickle.dumps(e1, proto)
e2 = pickle.loads(pickled)
self.assertEqual(e1.message, e2.message)
self.assertEqual(e1.args, e2.args)
self.assertEqual(e1.line, e2.line)
self.assertEqual(e1.filename, e2.filename)
self.assertEqual(e1.lineno, e2.lineno)
self.assertEqual(repr(e1), repr(e2))
示例6: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def __init__(self, defaults=None, confFile=None, *args, **kwds):
"""Initialize the parser.
*defaults* -- defaults values.
*confFile* -- the file (or list of files) to parse."""
ConfigParser.ConfigParser.__init__(self, defaults=defaults)
if confFile is None:
dotFileName = '.' + confFileName
# Current and home directory.
confFile = [os.path.join(os.getcwd(), confFileName),
os.path.join(os.getcwd(), dotFileName),
os.path.join(os.path.expanduser('~'), confFileName),
os.path.join(os.path.expanduser('~'), dotFileName)]
if os.name == 'posix':
sep = getattr(os.path, 'sep', '/')
# /etc/ and /etc/conf.d/
confFile.append(os.path.join(sep, 'etc', confFileName))
confFile.append(os.path.join(sep, 'etc', 'conf.d',
confFileName))
else:
# etc subdirectory of sys.prefix, for non-unix systems.
confFile.append(os.path.join(sys.prefix, 'etc', confFileName))
for fname in confFile:
try:
self.read(fname)
except (ConfigParser.MissingSectionHeaderError,
ConfigParser.ParsingError), e:
_aux_logger.warn('Troubles reading config file: %s' % e)
# Stop at the first valid file.
if self.has_section('imdbpy'):
break
示例7: get_local_facts_from_file
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def get_local_facts_from_file(filename):
""" Retrieve local facts from fact file
Args:
filename (str): local facts file
Returns:
dict: the retrieved facts
"""
local_facts = dict()
try:
# Handle conversion of INI style facts file to json style
ini_facts = ConfigParser.SafeConfigParser()
ini_facts.read(filename)
for section in ini_facts.sections():
local_facts[section] = dict()
for key, value in ini_facts.items(section):
local_facts[section][key] = value
except (ConfigParser.MissingSectionHeaderError,
ConfigParser.ParsingError):
try:
with open(filename, 'r') as facts_file:
local_facts = json.load(facts_file)
except (ValueError, IOError):
pass
return local_facts
示例8: test_missingsectionheadererror
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def test_missingsectionheadererror(self):
import pickle
e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line')
pickled = pickle.dumps(e1)
e2 = pickle.loads(pickled)
self.assertEqual(e1.message, e2.message)
self.assertEqual(e1.args, e2.args)
self.assertEqual(e1.line, e2.line)
self.assertEqual(e1.filename, e2.filename)
self.assertEqual(e1.lineno, e2.lineno)
self.assertEqual(repr(e1), repr(e2))
示例9: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def __init__(self, filename, section, defaults = None):
if defaults is None:
defaults = {}
ConfigParser.__init__(self)
self.defaults = defaults
self.defaultvalues = {'string': '',
'int': 0,
'float': 0.0,
'boolean': False,
'color': None,
'bencode-list': [],
'bencode-string': '',
'bencode-fontinfo': {'name': None,
'size': None,
'style': None,
'weight': None}}
self.filename = filename
self.section = section
dirname = os.path.dirname(self.filename)
if not os.access(dirname, os.F_OK):
os.makedirs(dirname)
if filename.endswith('abc.conf') and not os.access(filename, os.F_OK):
defaults['minport'] = str(DEFAULTPORT)
try:
self.read(self.filename)
except MissingSectionHeaderError:
oldfile = open(self.filename, 'r')
oldconfig = oldfile.readlines()
oldfile.close()
newfile = open(self.filename, 'w')
newfile.write('[' + self.section + ']\n')
newfile.writelines(oldconfig)
newfile.close()
self.read(self.filename)
except ParsingError:
self.tryRepair()
self.read(self.filename)
示例10: testConfig
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def testConfig(self, goodconfig, newline, passes = 0):
if newline:
testconfig = goodconfig + newline + '\r\n'
newfile = StringIO(testconfig)
try:
testparser = ConfigParser()
testparser.readfp(newfile)
return testconfig
except MissingSectionHeaderError:
if passes > 0:
return goodconfig
else:
return self.testConfig(goodconfig + '[' + self.section + ']\n', newline, passes=1)
except ParsingError:
return goodconfig
示例11: get_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def get_config():
"""
Tries to find config options in the platform-specific user config file,
otherwise falls back to defaults.
"""
config_dir = get_config_dir()
config_file = os.path.join(config_dir, "newdoc.ini")
# Copy default options to start with:
options = DEFAULT_OPTIONS
# Search for matching keys in the config file; if found,
# update the options dict with them
if os.path.isfile(config_file):
config = cp.ConfigParser()
try:
config.read(config_file)
except cp.MissingSectionHeaderError:
print("Error: The [newdoc] section is required in the configuration file.")
exit(1)
for k in options.keys():
# The configparser library is different in Python 2 and 3.
# This si the only 2/3-compatible way I've found for optional keys.
try:
options[k] = config.get("newdoc", k)
except cp.NoOptionError:
pass
return options
# def convert_title_to_id(title: str, doc_type: str) -> str:
示例12: read_system_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def read_system_config(path=SYSTEM_CONFIG_PATH):
"""Parse and return the system config settings in /etc/uwallet.conf."""
result = {}
if os.path.exists(path):
p = ConfigParser.ConfigParser()
try:
p.read(path)
for k, v in p.items('client'):
result[k] = v
except (ConfigParser.NoSectionError, ConfigParser.MissingSectionHeaderError):
pass
return result
示例13: test_parse_errors
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def test_parse_errors(self):
self.newconfig()
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n extra-spaces: splat\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n extra-spaces= splat\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\noption-without-value\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n:value-without-option-name\n")
self.parse_error(ConfigParser.ParsingError,
"[Foo]\n=value-without-option-name\n")
self.parse_error(ConfigParser.MissingSectionHeaderError,
"No Section!\n")
示例14: _read_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def _read_config(filename):
"""Returns a RawConfigParser that has parsed the config file specified by
the passed filename."""
# check for bad config files
p = RawConfigParser()
fp = None
try:
fp = open(filename)
except IOError:
pass
if fp is not None:
try:
p.readfp(fp, filename=filename)
except MissingSectionHeaderError:
fp.close()
del fp
bad_config(filename)
except ParsingError:
fp.close()
del fp
bad_config(filename)
else:
fp.close()
return p
示例15: read
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import MissingSectionHeaderError [as 别名]
def read(self, filenames): # pylint: disable=W0221
"""Read and parse a filename or a list of filenames.
Overridden from ConfigParser and modified so as to allow options
which are not inside any section header
Return list of successfully read files.
"""
if isinstance(filenames, str):
filenames = [filenames]
read_ok = []
for priority, filename in enumerate(filenames):
try:
out_file = io.StringIO()
for line in codecs.open(filename, encoding='utf-8'):
line = line.strip()
match_obj = self.OPTCRE.match(line)
if not self.SECTCRE.match(line) and match_obj:
optname, delimiter, optval = match_obj.group('option',
'vi',
'value')
if optname and not optval and not delimiter:
out_file.write(line + "=\n")
else:
out_file.write(line + '\n')
else:
out_file.write(line + '\n')
out_file.seek(0)
except IOError:
continue
try:
self._read(out_file, filename)
for group in self._sections.keys():
try:
self._options_dict[group]
except KeyError:
self._options_dict[group] = {}
for option, value in self._sections[group].items():
self._options_dict[group][option] = (value, priority)
self._sections = self._dict()
except MissingSectionHeaderError:
self._read(out_file, filename)
out_file.close()
read_ok.append(filename)
return read_ok