用python读取配置文件config.ini

Posted wutantan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用python读取配置文件config.ini相关的知识,希望对你有一定的参考价值。

还在学习中。。。写的有点凌乱

感觉还是应该先学会读取配置文件才行,把一些经常需要修改的但是又经常需要用到的参数放到配置文件中方便使用(我是这么觉得的)

 

首先是config.ini的存放位置,我们把它放在根目录下(当然也可以随便想放哪放哪)

1 proDir = os.path.split(os.path.realpath(__file__))[0] //根目录地址 
2 configPath = os.path.join(proDir, "config.ini") //存放在根目录下,文件名是config.ini

config.ini的内容如下:

 1 [EMAIL]
 2 mail_host = smtp.163.com
 3 mail_user = [email protected].com
 4 mail_pass = 123456
 5 mail_port = 25
 6 sender = [email protected].com
 7 receiver = [email protected]/1254367@qq.com
 8 subject = Interface Test Report
 9 content = "All interface test has been complited
please read the report file about the detile of result in the attachment."
10 testuser = Someone
11 on_off = off
12 
13 [HTTP]
14 scheme = http
15 baseurl = www.baidu.com
16 port = 8080
17 timeout = 10.0
18 
19 [HEADERS]
20 siteuid = all
21 clientid = 100
22 token_v = 213612368807
23 token_u = 320012369021
24 
25 [DATABASE]
26 host = localhost
27 username = root
28 password = root
29 port = 3306
30 database = test

既然配置文件有了,我们就来读取配置文件吧

 1 import os
 2 import codecs
 3 import configparser
 4 
 5 proDir = os.path.split(os.path.realpath(__file__))[0]
 6 configPath = os.path.join(proDir, "config.ini")
 7 
 8 
 9 class ReadConfig:
10     def __init__(self):
11         fd = open(configPath)
12         data = fd.read()
13 
14         #  remove BOM
15         if data[:3] == codecs.BOM_UTF8:
16             data = data[3:]
17             file = codecs.open(configPath, "w")
18             file.write(data)
19             file.close()
20         fd.close()
21 
22         self.cf = configparser.ConfigParser()
23         self.cf.read(configPath)
24 
25     def get_email(self, name):
26         value = self.cf.get("EMAIL", name)
27         return value
28 
29     def get_http(self, name):
30         value = self.cf.get("HTTP", name)
31         return value
32 
33     def get_headers(self, name):
34         value = self.cf.get("HEADERS", name)
35         return value
36 
37     def set_headers(self, name, value):
38         self.cf.set("HEADERS", name, value)
39         with open(configPath, w+) as f:
40             self.cf.write(f)
41 
42     def get_url(self, name):
43         value = self.cf.get("URL", name)
44         return value
45 
46     def get_db(self, name):
47         value = self.cf.get("DATABASE", name)
48         return value

 

以上是关于用python读取配置文件config.ini的主要内容,如果未能解决你的问题,请参考以下文章

Python读取配置文件(config.ini),写入配置文件

python 读取ini 配置文件

python读取ini配置文件+Scala读取配置文件

python读取配置文件的方式

python读取ini配置文件

Python+Selenium进行UI自动化测试项目中,常用的小技巧2:读取配置文件(configparser,.ini文件)