当前位置: 首页>>代码示例>>Python>>正文


Python ConfigParser.MissingSectionHeaderError方法代码示例

本文整理汇总了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 
开发者ID:mazaclub,项目名称:encompass,代码行数:21,代码来源:simple_config.py

示例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") 
开发者ID:IndicoDataSolutions,项目名称:IndicoIo-python,代码行数:24,代码来源:config.py

示例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) 
开发者ID:olofk,项目名称:fusesoc,代码行数:40,代码来源:fusesocconfigparser.py

示例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") 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:14,代码来源:test_cfgparser.py

示例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)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:14,代码来源:test_cfgparser.py

示例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 
开发者ID:skarlekar,项目名称:faces,代码行数:33,代码来源:__init__.py

示例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 
开发者ID:openshift,项目名称:origin-ci-tool,代码行数:29,代码来源:openshift_facts.py

示例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)) 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:13,代码来源:test_cfgparser.py

示例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) 
开发者ID:alesnav,项目名称:p2ptv-pi,代码行数:39,代码来源:configreader.py

示例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 
开发者ID:alesnav,项目名称:p2ptv-pi,代码行数:17,代码来源:configreader.py

示例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: 
开发者ID:redhat-documentation,项目名称:tools,代码行数:35,代码来源:newdoc.py

示例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 
开发者ID:UlordChain,项目名称:Uwallet,代码行数:15,代码来源:simple_config.py

示例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") 
开发者ID:ofermend,项目名称:medicare-demo,代码行数:16,代码来源:test_cfgparser.py

示例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 
开发者ID:kenorb-contrib,项目名称:BitTorrent,代码行数:29,代码来源:configfile.py

示例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 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:49,代码来源:optionfiles.py


注:本文中的ConfigParser.MissingSectionHeaderError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。