學習接口測試時,當我把配置文件xx.config和讀取配置文件的模塊read_config.py放在項目下的同一個包config裏時,只需傳入文件名xx.config便可實現對配置文件的讀取. 可是當我在項目下另外一個包裏導入read_config.py後,再次傳入要讀取的配置文件名xx.config,卻報錯了!學習
Traceback (most recent call last): File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 1138, in _unify_values sectiondict = self._sections[section] KeyError: 'MOD' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/develop/lemon/tool/read_excel.py", line 88, in <module> button = ReadConfig().read_config('case.config','MOD','button') File "C:\develop\lemon\config\read_config.py", line 18, in read_config return cf.get(section,option) File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 781, in get d = self._unify_values(section, vars) File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 1141, in _unify_values raise NoSectionError(section) configparser.NoSectionError: No section: 'MOD'
糾結了半天,始終找不出錯誤緣由,想去百度一下,可是心想這麼簡單的問題難道我都解決不了還要去百度?那豈不是太沒面子了呀! 我打開酷狗,放一首古琴曲, 試着讓本身靜下來,但窗外馬路上的汽車鳴笛聲讓我靜不下來, 忽然發現, 會不會是路徑有問題?測試
read_config部分以下:spa
class ReadConfig: def read_config(self,file_name,section,option): cf = configparser.ConfigParser() cf.read(file_name,encoding='utf-8') return cf.get(section,option) if __name__ == '__main__': r = ReadConfig().read_config('case.config','MOD','button') print(r)
將尋找配置文件的路徑改了一下,加了一行, 讓你無論輸入什麼配置文件名都去config包裏面去找:excel
class ReadConfig: def read_config(self,file_name,section,option): file = os.path.abspath(os.path.join(os.getcwd(),'..','config',file_name)) cf = configparser.ConfigParser() cf.read(file,encoding='utf-8') return cf.get(section,option) if __name__ == '__main__': r = ReadConfig().read_config('case.config','MOD','button') print(r)
大功告成, 哈code