1、ConfigParser模块在python中用来读取配置文件,配置文件的格式跟Windows下的ini配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序中写死,增加程序的灵活性;
备注:python3中ConfigParser模块名已更为configparser;
configparser函数常用方法:
读取配置文件:
read(filename) #读取配置文件,直接读取ini文件内容 section() #获取ini文件内所有的section,以列表形式返回['logging','mysql'] options(sections) #获取指定sections下所有options,以列表形式返回['host','port','user','password'] items(sections) #获取指定section下所有的键值对[('host','127.0.0.1'),('port','3306'),('user','root'),('password','123456')] get(section,option) #获取section中option的值,返回string类型示例如下:
配置文件ini如下:
[logging] level = 20 path = server = [mysql] host=127.0.0.1 port=3306 user=root password=123456 其中,=号可以使用:替换 import configparser from until.file_system import get_init_path conf = configparser.ConfigParser() file_path = get_init_path() print('file_path :',file_path) conf.read(file_path) sections = conf.sections() print('获取配置文件所有的section', sections) options = conf.options('mysql') print('获取指定section下所有option', options) items = conf.items('mysql') print('获取指定section下所有的键值对', items) value = conf.get('mysql', 'host') print('获取指定的section下的option', type(value), value)运行结果如下:
file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini 获取配置文件所有的section ['logging', 'mysql'] 获取指定section下所有option ['host', 'port', 'user', 'password'] 获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 获取指定的section下的option <class 'str'> 127.0.0.1综合使用方法:
import configparser """ 读取配置文件信息 """ class ConfigParser(): config_dic = {} @classmethod def get_config(cls, sector, item): value = None try: value = cls.config_dic[sector][item] except KeyError: cf = configparser.ConfigParser() cf.read('settings.ini', encoding='utf8') #注意setting.ini配置文件的路径 value = cf.get(sector, item) cls.config_dic = value finally: return value if __name__ == '__main__': con = ConfigParser() res = con.get_config('logging', 'level') print(res) import configparser def getReqParams(filename): """ # 获取请求参数 :param file: 配置文件,格式为ini格式 :return: 返回key:value结构参数串 """ newParams = {} conf = configparser.ConfigParser() conf.read(filename) for key, value in conf.items("mysql"): if value != "": newParams[key] = value for key, value in conf.items("logging"): if value != "": newParams[key] = value return newParams print(getReqParams('D:\ceshi.ini')) 返回结果: {'host': '127.0.0.1', 'port': '3306', 'user': 'root', 'password': '123456', 'level': '20', 'path': "'dsfsadf'", 'server': "'fasfsaf'"}
2、python中json模块dumps、loads、dump、load函数详细介绍
json.dumps()函数用于将dict类型的数据转成str,因为如果直接将dict数据写入json文件会报错,所以需要该函数转化数据:
import json name_emb = {'a':'1111','b':'2222','c':'3333'} isObj = json.dumps(name_emb) print(name_emb) print(isObj) print(type(name_emb)) print(type(isObj)) 执行结果: {'a': '1111', 'b': '2222', 'c': '3333'} {"a": "1111", "b": "2222", "c": "3333"} <class 'dict'> <class 'str'>若在数据写入json文件时,未先进行转换,报错如下:
import json name_emb = {'a':'1111','b':'2222','c':'3333'} emb_filename = ('d://emb.json') with open(emb_filename,'w') as f: f.write(name_emb) f.close() 报错如下: Traceback (most recent call last): File "d:/user/01369530/桌面/123123.py", line 5, in <module> f.write(name_emb) TypeError: write() argument must be str, not dict 更改后的代码如下: import json name_emb = {'a':'1111','b':'2222','c':'3333'} emb_filename = ('d://emb.json') with open(emb_filename,'w') as f: f.write(json.dumps(name_emb)) f.close()json.loads()用于将str类型的数据转换成dict:
import json name_emb={'a':'1111','b':'2222','c':'3333','d':'4444'} jsDumps=json.dumps(name_emb) jsLoads=json.loads(jsDumps) print(name_emb) print(jsDumps) print(jsLoads) print(type(name_emb)) print(type(jsDumps)) print(type(jsLoads))json.dump():用于将dict类型的数据转成str,并写入到json文件中。下面两种方法都可以将数据写入json中;
import json name_emb = {'a':'1111','b':'2222','c':'3333','d':'4444'} emb_filename = ('/home/cqh/faceData/emb_json.json') # solution 1 jsObj = json.dumps(name_emb) with open(emb_filename, "w") as f: f.write(jsObj) f.close() # solution 2 json.dump(name_emb, open(emb_filename, "w"))json.load():用于从json文件中读取数据
import json emb_filename = ('/home/cqh/faceData/emb_json.json') jsObj = json.load(open(emb_filename)) print(jsObj) print(type(jsObj)) for key in jsObj.keys(): print('key: %s value: %s' % (key,jsObj.get(key))) def getJsonFromFile(filename): """ # 从json文件中获取请求参数 :param filename: 配置文件,格式为json :return: 返回json串 """ try: if isfile(filename): return json.load(open(filename,'r', encoding='UTF-8')) else: return None except Exception as e: logging.warning("%s -- The json file is Wrong! Pleas check file: %s" % (e, filename)) return None3、paramiko模块,基于SSH用于连接远程服务器并执行相关操作
该模块可以用于连接远程服务器并执行基本命令: