Python之读取配置文件

来源:互联网 发布:三国杀卧龙诸葛亮知乎 编辑:程序博客网 时间:2024/06/07 21:09

Python之读取配置文件

在我们编写基于Appium框架的自动化测试脚本时,我们可以把初始化中用到的参数放到配置文件中来维护读写

一、ConfigParser简介

Python自带的模块,用来读取配置文件的包。

配置文件格式:

[oppo]platformName = AndroidplatformVersion = 6.0deviceName = 2a22ceeappPackage = com.sina.weiboappActivity = .SplashActivityurl = http://127.0.0.1:4723/wd/hub

其中中括号中的是section
section下是以key=value 格式的键值对

二、常用方法

  1. 创建ConfigParser实例
config=ConfigParser.ConfigParser()
  1. 读取配置文件
config.read(filename)
  1. 返回某个项目中的所有键的序列
config.options(section)
  1. 返回section中的option的键值
config.get(section,option)
  1. 添加一个配置文件的section节点
config.add_section(section-name)
  1. 设置某个section中键名为option的值
config.set(section,option,val)
  1. 返回配置文件中所有的section
config.section()
  1. 写入配置文件
config.write(obj_file)

三、应用实例

# -*- coding: utf-8 -*-import unittestfrom time import sleepfrom appium import webdriverimport ConfigParserclass TestPlan(unittest.TestCase):    def setUp(self):        conf = ConfigParser.SafeConfigParser()        conf.read("Conf\\config.ini")        desired_caps = {}        desired_caps['platformName'] = conf.get("oppo", "platformName")        desired_caps['deviceName'] = conf.get("oppo", "deviceName")        desired_caps['appPackage'] = conf.get("oppo", "appPackage")        desired_caps['appActivity'] = conf.get("oppo", "appActivity")        self.driver = webdriver.Remote(conf.get("oppo", "url"), desired_caps)        self.driver.implicitly_wait(5)    def testLogin(self):        sleep(10)        self.driver.find_element_by_id(id_="tab_center_layout").click()        el_username = self.driver.find_element_by_id(id_="userName")        el_password = self.driver.find_element_by_id(id_="userPwd")        el_username.send_keys("13800138000")        el_password.send_keys("qwer1234")        self.driver.find_element_by_id(id_="submitbtn").click()    def tearDown(self):        self.driver.quit()if __name__ == '__main__':    unittest.main()
原创粉丝点击