我的配置文件中有类似的内容(一个包含字符串列表的配置选项):
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
是否有一种更优雅(内置)的方式从 filtersToCheck 获取列表,而不是删除括号、单引号、空格然后使用split()
来执行此操作?也许是一个不同的模块?
(使用python3。)
我的配置文件中有类似的内容(一个包含字符串列表的配置选项):
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
是否有一种更优雅(内置)的方式从 filtersToCheck 获取列表,而不是删除括号、单引号、空格然后使用split()
来执行此操作?也许是一个不同的模块?
(使用python3。)
您不能在配置文件的值中像列表一样使用 python 对象。但是你当然可以将它们作为逗号分隔的值,一旦你得到它就进行拆分
[filters]
filtersToCheck = foo,192.168.1.2,barbaz
做
filtersToCheck = value.split(',')
当然,另一种方法是继承 SafeConfigParser 类并删除 [ 和 ] 并构造列表。您将此称为丑陋,但这是一个可行的解决方案。
The third way is to use Python module as a config file. Projects do this. Just have the filtersToCheck as a variable available from your config.py module and use the list object. That is a clean solution. Some people are concerned about using python file as config file (terming it as security hazard, which is somewhat an unfounded fear), but there also this group who believe that users should edit config files a not python files which serve as config file.
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
结果
name : a_string
value: something
type : <type 'str'>
name : filtersToCheck
value: ['foo', '192.168.1.2', 'barbaz']
type : <type 'list'>
name : a_tuple
value: (145, 'kolo', 45)
type : <type 'tuple'>
然后
li = [ (mat.group(1),eval(mat.group(2))) for mat in regx.finditer(ss)]
print li
结果
[('a_string', 'something'), ('filtersToCheck', ['foo', '192.168.1.2', 'barbaz']), ('a_tuple', (145, 'kolo', 45))]