python操作配置文件

来源:互联网 发布:linux脚本 echo 编辑:程序博客网 时间:2024/06/06 02:12

从配置文件中读取程序所需的参数等信息。步骤:

1、导入: import ConfigParser

2、打开配置文件,配置文件test.conf要和py文件在同一目录下,否则需指定配置文件所在的目录:

cf = ConfigParser.ConfigParser() 

cf.read("test.conf")  

3、读配置文件信息

db2_database = cf.get("DB2", "DATABASE")  

db2_hostname = cf.get("DB2", "HOSTNAME")  

db2_port     = cf.get("DB2", "PORT")  

db2_protocol = cf.get("DB2", "PROTOCOL") 

db2_uid      = cf.get("DB2", "UID")

db2_pwd      = cf.get("DB2", "PWD")

注意:cf.get返回的是字符串,如果要返回整型可用sf.getint

完整的脚本如下

#-*- encoding: utf-8 -*-  import ConfigParser,stringimport ibm_db# read config filecf = ConfigParser.ConfigParser()  cf.read("test.conf")  db2_database = cf.get("DB2", "DATABASE")  db2_hostname = cf.get("DB2", "HOSTNAME")  db2_port     = cf.get("DB2", "PORT")  db2_protocol = cf.get("DB2", "PROTOCOL") db2_uid      = cf.get("DB2", "UID")db2_pwd      = cf.get("DB2", "PWD")

配置文件格式如下

[DB2]  DATABASE=dbnameHOSTNAME=hostnamePORT=50000PROTOCOL=TCPIPUID=uidPWD=pwd[concurrent]  thread=10 processor=20