Python讀取ini文件需要用到 ConfigParser 模塊
關於ConfigParser模塊的介紹詳情請參照官網解釋:https://docs.python.org/2.7/library/configparser.html
- 要讀取的ini文件(configfile.ini)如下:
- 以"[browserType ]"做section,browserName 為options
[browserType] #browserName = Firefox browserName = Chrome #browserName = IE [account] user = test1 #user = admin [language] language = EN #language = CN [country] country = US #country = FR #country = IT
- get(section,option) 得到section中option的值,返回為string類型
- 在自動化測試框架中讀取每個配置文件中的值,並返回以做調用或者拼接
import ConfigParser
class ReadConfigFile(object): def get_value(self): config = ConfigParser.ConfigParser() config.read("configfile.ini") browserName = config.get('browserType','browserName') account = config.get('accountType','user') language = config.get('languageType','language') country = config.get('countryType','country') return [browserName,account,language,country] trcf = ReadConfigFile() print '***********************************' print trcf.get_value() print '***********************************'

