Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用ConfigParser从配置文件获取列表_Python_List_Python 3.x_Configuration Files_Configparser - Fatal编程技术网

Python 使用ConfigParser从配置文件获取列表

Python 使用ConfigParser从配置文件获取列表,python,list,python-3.x,configuration-files,configparser,Python,List,Python 3.x,Configuration Files,Configparser,我的配置文件中有类似的内容(一个包含字符串列表的配置选项): 是否有一种更优雅(内置)的方法从filtersToCheck获取列表,而不是删除括号、单引号和空格,然后使用split()来实现这一点?也许是另一个模块 (使用python3。) 结果 name : a_string value: something type : <type 'str'> name : filtersToCheck value: ['foo', '192.168.1.2', 'barbaz'] type

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

是否有一种更优雅(内置)的方法从filtersToCheck获取列表,而不是删除括号、单引号和空格,然后使用
split()
来实现这一点?也许是另一个模块

(使用python3。)

结果

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'>
[('a_string', 'something'), ('filtersToCheck', ['foo', '192.168.1.2', 'barbaz']), ('a_tuple', (145, 'kolo', 45))]
结果

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'>
[('a_string', 'something'), ('filtersToCheck', ['foo', '192.168.1.2', 'barbaz']), ('a_tuple', (145, 'kolo', 45))]

不能像在配置文件的值中使用列表一样使用python对象。但你们当然可以把它们作为逗号分隔的值,一旦你们得到它,就进行拆分

[filters]
filtersToCheck = foo,192.168.1.2,barbaz

filtersToCheck = value.split(',')
当然,另一种方法是对SafeConfigParser类进行子类化,删除[and]并构造列表。你称之为丑陋,但这是一个可行的解决方案


第三种方法是使用Python模块作为配置文件。项目就是这样做的。只需将filtersToCheck作为config.py模块中可用的变量,并使用list对象即可。这是一个干净的解决方案。有些人担心使用python文件作为配置文件(称之为安全隐患,这是一种毫无根据的担忧),但也有一些人认为用户应该编辑配置文件,而不是作为配置文件的python文件。

可能重复:在我看来,这是不一样的。。我知道这是可以做到的,但我正在寻找一种更优雅的方式来做到这一点。。除此之外,这个链接已经有3年历史了,从那时起Python作为一种语言发生了很多事情。如果你的意思是这样的话,ConfigParser模块还没有被更新来处理这个用例。但您仍然可以对其进行子类化,以检查字符串中的
,如果是,还可以对其进行
拆分。这完全相同,用于链接中问题的解决方案在这里也起作用。使用json.loads+configParser或ast+configParser的解决方案基本上是一行,在一般情况下可以工作(例如,使用字典)。除非你找到一个他们失败的案例,否则就是这样做的。我的案例中没有安全问题。我看到的唯一问题是我需要用我的脚本制作一个可执行文件(使用cxfreeze)。。我不确定python模块(与可执行文件位于同一文件夹中)在这种情况下是否可以工作?我想可能不会,因为cxfreeze也会编译它。cxfreeze没有任何忽略选项吗?没想到!它有“-exclude modules”。我试试看,然后报告结果。谢谢你的主意。
filtersToCheck = value.split(',')