ConfigParser
requires all sections, keys and values to be strings; no surprise. It has methods to convert the values to datatypes with getfloat
, getint
, getboolean
. If you don't know the datatype, you can wrap the get()
with an eval()
to get have the string evaluated such as:
ConfigParser要求所有部分、键和值都是字符串;没有惊喜。它使用getfloat、getint和getboolean方法将值转换为数据类型。如果不知道数据类型,可以使用eval()将get()包装起来,使字符串得到计算,例如:
>>> from ConfigParser import SafeConfigParser
>>> cp = SafeConfigParser()
>>> cp.add_section('one')
>>> cp.set('one', 'key', '42')
>>> print cp.get('one', 'key')
'42'
>>> print eval(cp.get('one', 'key'))
42
>>> cp.set('one', 'key', 'None')
>>> print eval(cp.get('one', 'key'))
None
>>>
Is there a better way? I assume there some grave security concerns with evaluating text from a file- which I acknowledge; I completely trust the file.
有更好的方法吗?我认为在评估文件文本时存在一些严重的安全问题——我承认这一点;我完全相信这个文件。
I thought I would use pickle
for this, but I would really like to keep the config file human readable.
我想我应该用pickle来处理这个问题,但是我真的很想让配置文件人类可读。
How would you do it?
你会怎么做?
4 个解决方案
#1
13
If you are using Python 2.6 or above you can use ast.literal_eval
:
如果您使用的是Python 2.6或更高版本,可以使用ast.literal_eval:
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.literal_eval(node_or_string)安全地计算表达式节点或包含Python表达式的字符串。提供的字符串或节点可能只包含以下Python文字结构:字符串、数字、元组、列表、命令、布尔值和None。
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
这可以用于安全地计算包含来自不受信任源的Python表达式的字符串,而不需要自己解析这些值。
This will work like eval
when the string is safe:
这将像eval一样工作,当字符串是安全的:
>>> literal_eval("{'key': 10}")
{'key': 10}
But it will fail if anything besides the types listed in the documentation appear:
但如果出现文件中列出的类型以外的任何内容,它将失败:
>>> literal_eval("import os; os.system('rm -rf somepath')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib64/python2.6/ast.py", line 37, in parse
return compile(expr, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
import os; os.system('rm -rf somepath')
^
SyntaxError: invalid syntax
#2
3
For those that may be looking for another easier answer, instead of having to convert the data types yourself, you can use the localconfig module that does the conversion for you. The conversion is done by guessing the data type based on the value (I.e. 123 is an int, 123.4 is a float, true is a bool, and so on).
对于那些可能正在寻找另一个更简单的答案的人来说,您可以使用localconfig模块来为您进行转换,而不必自己转换数据类型。转换是通过猜测基于值的数据类型来完成的(例如123是int, 123.4是float, true是bool,等等)。
Here is an example following the OP's:
下面是OP的一个例子:
>>> from localconfig import config
>>> config.read('[one]\nkey = 42\nkey2 = None')
>>> config.one.key, type(config.one.key)
(42, <type 'int'>)
>>> config.one.key2, type(config.one.key2)
(None, <type 'NoneType'>)
>>> config.get('one', 'key'), config.get('one', 'key2')
(42, None)
It is a wrapper on top of ConfigParser, so it is fully compatible.
它是ConfigParser之上的包装器,所以它是完全兼容的。
Check it out at https://pypi.python.org/pypi/localconfig
在https://pypi.python.org/pypi/localconfig中查看它。
#3
1
If you are on 2.7+ then you can use the .getint
.getfloat
.getbool
methods. You can learn more about them in the docs
如果您使用的是2.7+,那么可以使用.getint .getfloat .getbool方法。你可以在文档中了解更多。
So your application would use print cp.getint('one', 'key')
所以你的应用会使用print cp。getint('one', 'key')
#4
0
Checkout ConfigIt for more pythonic configuration options
检查ConfigIt以获得更多的python配置选项
https://github.com/barberj/ConfigIt
https://github.com/barberj/ConfigIt
#1
13
If you are using Python 2.6 or above you can use ast.literal_eval
:
如果您使用的是Python 2.6或更高版本,可以使用ast.literal_eval:
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.literal_eval(node_or_string)安全地计算表达式节点或包含Python表达式的字符串。提供的字符串或节点可能只包含以下Python文字结构:字符串、数字、元组、列表、命令、布尔值和None。
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
这可以用于安全地计算包含来自不受信任源的Python表达式的字符串,而不需要自己解析这些值。
This will work like eval
when the string is safe:
这将像eval一样工作,当字符串是安全的:
>>> literal_eval("{'key': 10}")
{'key': 10}
But it will fail if anything besides the types listed in the documentation appear:
但如果出现文件中列出的类型以外的任何内容,它将失败:
>>> literal_eval("import os; os.system('rm -rf somepath')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib64/python2.6/ast.py", line 37, in parse
return compile(expr, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
import os; os.system('rm -rf somepath')
^
SyntaxError: invalid syntax
#2
3
For those that may be looking for another easier answer, instead of having to convert the data types yourself, you can use the localconfig module that does the conversion for you. The conversion is done by guessing the data type based on the value (I.e. 123 is an int, 123.4 is a float, true is a bool, and so on).
对于那些可能正在寻找另一个更简单的答案的人来说,您可以使用localconfig模块来为您进行转换,而不必自己转换数据类型。转换是通过猜测基于值的数据类型来完成的(例如123是int, 123.4是float, true是bool,等等)。
Here is an example following the OP's:
下面是OP的一个例子:
>>> from localconfig import config
>>> config.read('[one]\nkey = 42\nkey2 = None')
>>> config.one.key, type(config.one.key)
(42, <type 'int'>)
>>> config.one.key2, type(config.one.key2)
(None, <type 'NoneType'>)
>>> config.get('one', 'key'), config.get('one', 'key2')
(42, None)
It is a wrapper on top of ConfigParser, so it is fully compatible.
它是ConfigParser之上的包装器,所以它是完全兼容的。
Check it out at https://pypi.python.org/pypi/localconfig
在https://pypi.python.org/pypi/localconfig中查看它。
#3
1
If you are on 2.7+ then you can use the .getint
.getfloat
.getbool
methods. You can learn more about them in the docs
如果您使用的是2.7+,那么可以使用.getint .getfloat .getbool方法。你可以在文档中了解更多。
So your application would use print cp.getint('one', 'key')
所以你的应用会使用print cp。getint('one', 'key')
#4
0
Checkout ConfigIt for more pythonic configuration options
检查ConfigIt以获得更多的python配置选项
https://github.com/barberj/ConfigIt
https://github.com/barberj/ConfigIt