x=5
print(eval('x+1',{'__builtins__': None}))
出现错误:
TypeError: 'NoneType' object is not subscriptable
为什么我会出现上述错误?
另外,如何为 eval() 函数指定几个内置方法?例如,只允许max
and min
功能。
来自内置文档: https://docs.python.org/3/library/builtins.html
的价值__builtins__
通常是这个模块[内置] https://docs.python.org/3/library/builtins.html或该模块的值__dict__
属性
要修复您的错误:
>>> print(eval('x+1',{'__builtins__': {'x': x}}))
要指定一些内置方法,请将其提供给__builtins__
>>> print(eval('min(1,2)',{'__builtins__': {'min': min}}))
然而,限制__builtins__
仍然不安全:参见https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)