文章来自《Python cookbook》.

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

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

描述

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     #返回一个字典,格式如下: key:     <section>.option>
  18     #                   value :  对应的值 
  19        
  20 
  21 
  22     config = config.copy(  )
  23     cp = ConfigParser.ConfigParser(  )
  24     cp.read(file)
  25     for sec in cp.sections(  ):
  26         name = string.lower(sec)
  27         for opt in cp.options(sec):
  28             config[name + "." + string.lower(opt)] = string.strip(
  29                 cp.get(sec, opt))
  30     return config
  31 
  32 if _ _name_ _=="_ _main_ _":
  33     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.

很多程序员使用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.

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

参考 See Also

Documentation for the ConfigParser module in the Library Reference.

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