且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

利用Python将Linux conf配置文件的内容解析成字典格式

更新时间:2022-10-06 12:07:52

Linux下许多配置文件除了ini格式的可以用python的ConfigParser模块外,可以自己编写一段简单的代码将只有“key=value”这样的conf配置文件解析成字典,利用字典的key可以轻松获取key对应的value。python实现起来方法比较简单,只要逐行读取配置文件,将每一个键值对写入字典即可。

python代码示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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--





本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1811598,如需转载请自行联系原作者