码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-02-05 00:34:51      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:读取配置   get   amp   sql   logging   文件中   ppp   路径   odi   

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模块

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

标签:读取配置   get   amp   sql   logging   文件中   ppp   路径   odi   

原文地址:http://blog.51cto.com/weiruoyu/2348756

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!