python读取配置文件 变量 ConfigParser模块

Python 读取写入配置文件很方便,可使用内置的 configparser 模块
配置文件:config.ini

[oppo]
platformName = Android
platformVersion = 6.0
deviceName = weiruoyu
appPackage = com.sina.weibo
appActivity = .SplashActivity
url = http://127.0.0.1:4723/wd/hub

[mysql]
host=127.0.0.1
port=3306
user=root
password=123456

[logging]
level = 20
path = /usr/test
server = 192.168.1.8

源码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import ConfigParser

# ########函数############

conf = ConfigParser.ConfigParser()

a = conf.read("config.ini")
print "config.inf = ", a

print conf.items("oppo")

secs = conf.sections()
print "secs=", secs

options = conf.options("mysql")
print "options=", options

items = conf.items("mysql")
print "items=", items

host = conf.get("mysql","host")
print "host=",host

输出:

config.inf =  ['config.ini']
[('platformname', 'Android'), ('platformversion', '6.0'), ('devicename', 'weiruoyu'), ('apppackage', 'com.sina.weibo'), ('appactivity', '.SplashActivity'), ('url', 'http://127.0.0.1:4723/wd/hub')]
secs= ['oppo', 'mysql', 'logging']
options= ['host', 'port', 'user', 'password']
items= [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
host= 127.0.0.1
[Finished in 0.1s]

参考如下:

cf.read("E:\Crawler\config.ini")  # 读取配置文件,如果写文件的绝对路径,就可以不用os模块

secs = cf.sections()  # 获取文件中所有的section(一个配置文件中可以有多个配置,如数据库相关的配置,邮箱相关的配置,
                        每个section由[]包裹,即[section]),并以列表的形式返回
print(secs)

options = cf.options("Mysql-Database")  # 获取某个section名为Mysql-Database所对应的键
print(options)

items = cf.items("Mysql-Database")  # 获取section名为Mysql-Database所对应的全部键值对
print(items)

host = cf.get("Mysql-Database", "host")  # 获取[Mysql-Database]中host对应的值
print(host)

参考网址如下:
python读取配置文件&&简单封装
python configparser模块

猜你喜欢

转载自blog.51cto.com/weiruoyu/2348756