文章来自《Python cookbook》.

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

-- 61.182.251.99 [2004-09-23 21:33:17]

1. 描述

Reading INI Configuration Files

读取INI配置文件

Credit: Dirk Holtwick

1.1. 问题 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.

程序需要读取配置文件。 不想用一个可能带有安全漏洞、有复杂格式或者这样那样错误的(自己开发的)模块实现此配置功能。

1.2. 解决 Solution

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

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

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

1.3. 讨论 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.

很多程序员使用Python模块作为配置文件, 但这样使得程序易被他人利用,或者在文件中引入语法错误。使用由Windows引入的(同样适用于类Unix平台--文件本身只是具有特定结构的文本文件)INI配置文件,可以使用上面的小脚本。

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:

一个INI文件看起来像这样:

[database]
user = dummy
password = tosca123

You can set the defaults in advance. Note that the keys of the dictionary are always lowercase.

可以预先设定缺省值。注意字典的键值都是小写的。

1.4. 参考 See Also

Documentation for the ConfigParser module in the Library Reference.

Python文档库参考 ConfigParser模块部分。