Linux下许多配置文件除了ini格式的可以用python的ConfigParser模块外,可以自己编写一段简单的代码将只有“key=value”这样的conf配置文件解析成字典,利用字典的key可以轻松获取key对应的value。python实现起来方法比较简单,只要逐行读取配置文件,将每一个键值对写入字典即可。
python代码示例如下:
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- import re from copy import deepcopy try: linux_type_dict = dict() with open('/etc/os-release', 'r') as f: linux_type_list = f.read().strip().split('\n') except IOError: pass else: if linux_type_list is not None: linux_type_list_to_purge = deepcopy(linux_type_list) # linux_type_list_to_purge = linux_type_list[:] # another implement, sames to deepcopy for member in linux_type_list_to_purge: if re.search('^#+.*', member) is not None: member_to_purge = member linux_type_list.remove(member_to_purge) for member in linux_type_list: sub_member = member.split('=') linux_type_dict[sub_member[0]] = sub_member[1].strip('"') print linux_type_dict print linux_type_dict['ID']
获取更多实用的bash shell或python shell,请查阅我的github项目https://github.com/DingGuodong/LinuxBashShellScriptForOps,里面包含了很多与运维相关的bash脚本和python脚本,此项目将持续更新!
tag:python parse linux config file,python解析配置文件,python list to dict
--end--