文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.99 [DateTime(2004-09-23T21:33:17Z)] TableOfContents

描述

Reading INI Configuration Files

读取INI配置文件

Credit: Dirk Holtwick

问题 Problem

You want to load a configuration file for your program, but you don't want to use a Python module for this purpose, as that might expose you to security risks or troublesome syntax and other errors in the module.

程序需要读取配置文件,但是不想使用可能带有安全漏洞、有复杂格式或者其他错误的模块。

解决 Solution

The standard ConfigParser library module gives us almost all we need to use INI files for configuration:

标准库模块ConfigParser几乎提供了解析INI配置文件所需的一切:

   1 import ConfigParser
   2 import string
   3 
   4 _ConfigDefault = {
   5     "database.dbms":            "mysql",
   6     "database.name":            "",
   7     "database.user":            "root",
   8     "database.password":        "",
   9     "database.host":            "127.0.0.1"
  10     }
  11 
  12 def LoadConfig(file, config={}):
  13     """
  14     returns a dictionary with keys of the form
  15     <section>.<option> and the corresponding values
  16     """
  17     config = config.copy(  )
  18     cp = ConfigParser.ConfigParser(  )
  19     cp.read(file)
  20     for sec in cp.sections(  ):
  21         name = string.lower(sec)
  22         for opt in cp.options(sec):
  23             config[name + "." + string.lower(opt)] = string.strip(
  24                 cp.get(sec, opt))
  25     return config
  26 
  27 if _ _name_ _=="_ _main_ _":
  28     print LoadConfig("some.ini", _ConfigDefault)

讨论 Discussion

Many people use Python modules as configuration files, but this may allow your program to be manipulated or let a syntax error come into that file. To use INI-style configuration files, which are known from Windows (but can also be used under Unix-like systems, since they're just text files with some structure), try the small script here.

The code in the recipe is just for reading configuration files, but writing them is also easy to implement. An INI file looks like this:

[database] user = dummy password = tosca123 You can set the defaults in advance. Note that the keys of the dictionary are always lowercase.

参考 See Also

Documentation for the ConfigParser module in the Library Reference.