config.cfg文件内容:
现需读取config.cfg里的host内容:
1 # @Time : 2021/9/4 20:21 3 # @File : readCfg.py 4 import os 5 6 from configparser import ConfigParser 7 import os 8 9 class ReadCfg(): 10 def __init__(self): 11 pass 12 13 def getPath(self): 14 #获取当前目录 15 current_dir = os.path.abspath(‘‘) 16 #获取上一级目录 17 filePath = os.path.dirname(current_dir) 18 #再获取上一级目录 19 lastFilePath = os.path.dirname(filePath) 20 #拼接配置文件的路径 21 cfgPath =os.path.join(lastFilePath,‘conf‘,‘config.cfg‘) 22 print(cfgPath) 23 return cfgPath 24 #默认获取主机的地址 25 def readCfg(self,section=‘hostname‘,option = ‘host‘): 26 #拼接配置文件的路径 27 con = ConfigParser() 28 con.read(self.getPath(),‘utf-8‘) 29 res = con.get(section,option) 30 return res 31 32 if __name__ == ‘__main__‘: 33 readCfg = ReadCfg()
原文:https://www.cnblogs.com/chooperman/p/15233142.html