python 如何读取config.ini中的配置信息-Python读取修改ini配置文件[ConfigParser]

使用到的包:ConfigParser 文档

需求

写个项目,用到数据库,多个地方使用,不能硬编码。很类似java的properties文件

Python支持ini文件的读取

ini文件

db_config.ini

[baseconf]

host=127.0.0.1

port=3306

user=root

password=root

db_name=evaluting_sys

[concurrent]

processor=20

示例代码

#!/usr/bin/python

# -*- coding:utf-8 -*-

#author: lingyue.wkl

#desc: use to db ops

#---------------------

#2012-02-18 created

#---------------------

import sys,os

import ConfigParser

def test(config_file_path):

cf = ConfigParser.ConfigParser()

cf.read(config_file_path)

s = cf.sections()

print "section:", s

o = cf.options("baseconf")

print "options:", o

v = cf.items("baseconf")

print "db:", v

db_host = cf.get("baseconf", "host")

db_port = cf.getint("baseconf", "port")

db_user = cf.get("baseconf", "user")

db_pwd = cf.get("baseconf", "password")

print db_host, db_port, db_user, db_pwd

cf.set("baseconf", "db_pass", "123456")

cf.write(open("config_file_path", "w"))

if __name__ == "__main__":

test("../conf/db_config.ini")

通用模块init_op.py

支持命令行+import两种

#!/usr/bin/python

# -*- coding:utf-8 -*-

#author: lingyue.wkl

#desc: use to read ini

#---------------------

#2012-02-18 created

#2012-09-02 changed for class support

#---------------------

import sys,os,time

import ConfigParser

class Config:

def __init__(self, path):

self.path = path

self.cf = ConfigParser.ConfigParser()

self.cf.read(self.path)

def get(self, field, key):

result = ""

try:

result = self.cf.get(field, key)

except:

result = ""

return result

def set(self, filed, key, value):

try:

self.cf.set(field, key, value)

cf.write(open(self.path,"w"))

except:

return False

return True

def read_config(config_file_path, field, key):

cf = ConfigParser.ConfigParser()

try:

cf.read(config_file_path)

result = cf.get(field, key)

except:

sys.exit(1)

return result

def write_config(config_file_path, field, key, value):

cf = ConfigParser.ConfigParser()

try:

cf.read(config_file_path)

cf.set(field, key, value)

cf.write(open(config_file_path,"w"))

except:

sys.exit(1)

return True

if __name__ == "__main__":

if len(sys.argv) < 4:

sys.exit(1)

config_file_path = sys.argv[1]

field = sys.argv[2]

key = sys.argv[3]

if len(sys.argv) == 4:

print read_config(config_file_path, field, key)

else:

value = sys.argv[4]

write_config(config_file_path, field, key, value)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值