1. 程式人生 > >python讀取配置文件 變量 ConfigParser模塊

python讀取配置文件 變量 ConfigParser模塊

config 數據 [] href crawler 寫文件 log parse items

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