使用ConfigParser从配置文件获取列表 [英] Getting a list from a config file with ConfigParser

查看:1065
本文介绍了使用ConfigParser从配置文件获取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的配置文件(一个包含字符串列表的配置选项)中有类似的内容:

[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']

是否有更优雅的(内置)方法从filtersToCheck获取列表,而不是删除方括号,单引号,空格然后使用split()来做到这一点?也许是其他模块吗?

(使用python3.)

解决方案

您不能在配置文件的值中使用python对象(如列表中的列表).但是您当然可以将它们作为逗号分隔的值,一旦获得,就进行分割

[filters]
filtersToCheck = foo,192.168.1.2,barbaz

然后做

filtersToCheck = value.split(',')

当然,另一种方法是将SafeConfigParser类子类化,然后删除[和]并构造列表.您称其为丑陋,但这是一个可行的解决方案.

第三种方法是将Python模块用作配置文件.项目可以做到这一点.只需让config.py模块中的filtersToCheck作为变量可用,然后使用列表对象即可.那是一个干净的解决方案.有些人担心将python文件用作配置文件(称其为安全隐患,这有点毫无根据),但还有一群人认为用户应该编辑配置文件而不是编辑用作配置文件的python文件. /p>

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', 'barbaz']

Is there a more elegant (built-in) way to get a list from filtersToCheck instead of removing the brackets, single-quotes, spaces and then using split() to do that? Maybe a different module?

(Using python3.)

解决方案

You cannot use the python object like a list in the value for the config file. But you can ofcourse have them as comma separated values and once you get it do a split

[filters]
filtersToCheck = foo,192.168.1.2,barbaz

and do

filtersToCheck = value.split(',')

The other approach is ofcourse, subclassing SafeConfigParser class and removing the [ and ] and constructing the list. You termed this as ugly, but this is a viable solution.

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.

这篇关于使用ConfigParser从配置文件获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆