python - 将 ConfigParser 值转换为 python 数据类型

标签 python eval configparser

ConfigParser 要求所有部分、键和值都是字符串;没有惊喜。它具有使用 getfloatgetintgetboolean 将值转换为数据类型的方法。如果您不知道数据类型,您可以用 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/

相关文章:

python - python 示例中的 dsl 需要像 ruby​​ 中一样

Python:使用 ConfigParser 与 json 文件

python - 使用python configparser读取没有键但有值条目的配置文件

python - python 如何计算 "is"表达式?

Python 计数抓取页面上的数字或字母

python - 为什么我的 tensorflow 代码运行这么慢?批量大小为 1

python数据结构(类似设置)在添加重复项时抛出异常

PHP计算使用变量

php - mysql - 存储嵌入代码(youtube、vimeo 等)

python - 从python中的.ini文件读取特殊字 rune 本