gpt4 book ai didi

python - 重写 ConfigParser get() 方法以包含 eval 有什么缺点吗?

转载 作者:行者123 更新时间:2023-12-01 06:14:13 25 4
gpt4 key购买 nike

我正在创建 ConfigParser 的子类,它更易于我在整个项目中使用:

class MyConfiguration(ConfigParser.ConfigParser):

def __init__(self, filename):
ConfigParser.ConfigParser.__init__(self)
self.readfp(open(filename))

def get(self, section, option):
return eval(ConfigParser.ConfigParser.get(self, section, option))

问题:使用包含 eval 的方法覆盖 get() 方法是否有任何缺点(安全性、意外后果)?

我宁愿将 eval 烘焙到 MyConfiguration 类中,因为我想在我的配置文件中使用 Python 数据类型(元组等),但我不想在我的项目代码中处理 eval。

最佳答案

如果您对 eval 的唯一兴趣是文字值,那么您可以使用 ast.literal_eval

这将读取元组文字、列表文字等,并且可以安全使用,因为它对接受的内容是有选择性的。

>>> import ast
>>> a = ast.literal_eval('(1, 2, 3)')
>>> a
(1, 2, 3)
>>> b = ast.literal_eval('__import__("evil")')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string

像这样的用例正是该函数的用途。

关于python - 重写 ConfigParser get() 方法以包含 eval 有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4177734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com