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
>>>
有没有更好的方法?我假设评估文件中的文本存在一些严重的安全问题——我承认;我完全信任该文件。
我想我会为此使用 pickle
,但我真的很想保持配置文件的可读性。
你会怎么做?
最佳答案
如果您使用的是 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.This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
当字符串安全时,这将像 eval
一样工作:
>>> literal_eval("{'key': 10}")
{'key': 10}
但如果出现文档中列出的类型之外的任何内容,它将失败:
>>> 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
关于python - 将 ConfigParser 值转换为 python 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6209094/