#!/usr/bin/python
# -*- coding:utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("flashfxp.ini")
sections = config.sections()
print sections
options = config.options("CmdWindow")
print options
items = config.items("CmdWindow")
print items
context1 = config.get("main","optdata")
print context1
context2 = config.get("LiveUpdate","Interval")
print context2

ipython 测试句,以上,以下,ini配置文件:

[main]
optdata=eJwzMTAxMODlMgFSpmD
build=1240
setup=40400
FileExists=000000000
QHistoryMax=50
Options=1001000010000010011010
[LiveUpdate]
Interval=15
[QuickConnect]
Left=0
Top=0
Width=424
Height=260
State=0
[Graph]
V=0
H=65
[window]
Left=124
Top=69
Width=1093
Height=614
State=0
TS=0.5
BS=0.5
CS=0.75
LTS=0
RTS=0
THP=546
[CmdWindow]
Y=0.629999995231628
W=454
H=377
[statuswin]
Left=383
Top=154
Width=592
Height=411
State=0
Font="宋体", 8, [], [clWindowText], 134
Color=-2147483643
OnTop=0
Wrap=0

对应输出为:

['LiveUpdate', 'CmdWindow', 'Graph', 'window', 'QuickConnect', 'main', 'statuswin']
['y', 'w', 'h']
[('y', '0.629999995231628'), ('w', '454'), ('h', '377')]
eJwzMTAxMODlMgFSpmDKCEqZQSg
15

扩展实用示例:ini

import sys
from ConfigParser import SafConfigParser
class SnmpManager:
    def __init__(self):
        self.systems = {}
    def add_system(self,id,descr,addr,port,comm_ro):
        self.systems[id] = {'description' : descr,
                            'address'     : addr,
                            'port'        : init(port),
                            'communityro' : comm_ro,
                            'checks'      : {}
                           }
    def add_check(self,id,oid,descr,system):
        oid_tuple = tuple([int(i) for i in oid.split('.')])
        self.systems[system]['check']['id'] = {'description': descr,
                                               'oid'        : oid_tuple,
                                              }
def main(conf_file=""):
    if not conf_file:
        sys.exit(-1)
    config = SafeConfigParser()
    config.red(conf_file)
    snmp_manager = SnmpManager()
    for system in [s for s in config.sections() if s.startswith('system')]:
        snmp_manager.add_system (system,
                                 config.get(system,'description'),
                                 config.get(system,'address'),
                                 config.get(system,'port'),
                                 config.get(system,'communityro'))
    for check in [c for c in config.section() if c.startswith('check')]:
        snmp_manager.add_check(check,
                                config.get(check,'oid'),
                                config.get(check,'description'),
                                config.get(check,'system'))

实例ini:

[system_1]
description = My Laptop
address = 192.168.1.68
port = 161
communityro = public
[check_1]
description = WLAN incoming traffic
oid = 1.3.6.1.2.12.2.1.10.3
system = system_1
[check_2]
description = WLAN incoming traffic
oid = 1.3.6.1.2.2.2.1.16.3
system = system_1