python - 读取自定义配置文件

时间:2015-08-24 06:18:43

标签: python python-2.7

如何使用python解析和生成如下格式化的配置文件?这三个部分可以有不同的顺序。

#black_ip
8.8.4.4
10.10.10.10
#white_ip
8.8.8.8
#threshold
180.149.132.47:6000

更新:

至于现在,我通过在python中使用以下re语句解决了这个问题:

   SECTCION = re.compile(
    r'\#'               # start with `#`
    r'(?P<header>\w+)'  #
   )

OPTION = re.compile(
    r'\s*(?P<ip>((0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5])\.){3}(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]))' # match the ip address
    r'(:)?'
    r'(?P<port>\d+)?\s*'    # match the port
)

这两个声明会很好地匹配它们。然后你需要做的是逐行扫描并匹配它们。

2 个答案:

答案 0 :(得分:1)

尝试使用configparser这个简单示例:

int departmentID = 0;
departmentID = Convert.ToInt32(form["department"])

 Employee entry = new Employee()
                {
                    firstname = form["firstname"],
                    lastname = form["lastname"],
                    department = departmentID

                };

运行结果:

import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('sample.conf')

black_ip = config.get('all', 'black_ip')
white_ip = config.get('all', 'white_ip')
threshold = config.get('all', 'threshold')
print black_ip, white_ip, threshold

答案 1 :(得分:0)

查看标准存储库中提供的python-configobj,它将完成配置文件所需的一切。
例如:

import os
from configobj import ConfigObj
configuration_dir = os.environ['HOME']
config_filename = configuration_dir + '/config.cfg'
if  os.access(config_filename, os.R_OK):
    pass
else:
    #if the file does not exist create and populate it
    cfg = ConfigObj(infile = config_filename, create_empty=True, write_empty_values=True, list_values=False)
    # define section control with a sub item in it
    cfg['control'] = {'TCP_PORT':'7000'}
    # define section Other with multiple sub items in it
    cfg['Other'] = {'parameter1':'','parameter2':''}
    cfg.write()

#Read the config file
cfg = ConfigObj(config_filename)
try:
    tcp_port = int(cfg['control']['TCP_PORT'])
    param1 = cfg['Other']['parameter1']
    param2 = cfg['Other']['parameter2']
except:
    tcp_port = 0
    param1 = ""
    param2 = ""
print tcp_port
print param1, param2

#Change the values in the config file
cfg['control']['TCP_PORT'] = '7000'
cfg['Other']['parameter1'] = 'parameter 1'
cfg['Other']['parameter2'] = 'parameter 2'
cfg.write()
print "Run program again to see changes"