Getting a list from a config file with ConfigParser

前端 未结 2 1377
日久生厌
日久生厌 2020-12-16 16:11

I have something like this in my config file (a config option that contains a list of strings):

[filters]
filtersToCheck = [\'foo\', \'192.168.1.2\', \'barba         


        
2条回答
  •  一整个雨季
    2020-12-16 17:01

    ss = """a_string = 'something'
    filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
       a_tuple =      (145,'kolo',45)"""
    
    import re
    regx = re.compile('^ *([^= ]+) *= *(.+)',re.MULTILINE)
    
    
    for mat in regx.finditer(ss):
        x = eval(mat.group(2))
        print 'name :',mat.group(1)
        print 'value:',x
        print 'type :',type(x)
        print
    

    result

    name : a_string
    value: something
    type : 
    
    name : filtersToCheck
    value: ['foo', '192.168.1.2', 'barbaz']
    type : 
    
    name : a_tuple
    value: (145, 'kolo', 45)
    type : 
    

    Then

    li = [ (mat.group(1),eval(mat.group(2))) for mat in regx.finditer(ss)]
    print li
    

    result

    [('a_string', 'something'), ('filtersToCheck', ['foo', '192.168.1.2', 'barbaz']), ('a_tuple', (145, 'kolo', 45))]
    

提交回复
热议问题