Python eval 错误抑制
首先,我意识到 eval 的缺点,它将用于我只想做的实验。
我正在创建一个脚本,其工作原理与暴力算法类似,但它不会破解密码,而是找到特殊形式的方程的解(不需要更多细节)。
会有很多字符串填充(通常在语法上不正确)术语,例如 1+2)+3
- 是通过 eval 获取这些术语结果的唯一方法吗?
- 如何让python忽略
eval
中发生的语法错误? (程序不应该终止)
First off, I'm aware of eval's disadvantages and it will be used in an experiment I want to make only.
I'm creating a script that works just like a Brute-Force algorithm but it won't break passwords but find the solution to a special form of an equation (more details are unnecessary).
There will be lots of strings filled with (often syntactically incorrect) terms like 1+2)+3
- Is the only way to get the results of these terms via
eval
? - How to make python ignore syntactical errors occurring in
eval
? (The program shouldn't terminate)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要抑制
SyntaxError
:To suppress
SyntaxError
:使用 ast 中的literal_eval 并捕获 ValueError 和 SyntaxError
use literal_eval from ast instead and catch ValueError and SyntaxError
除了 SyntaxError 之外,还有更多可能的异常:
ZeroDivisionError,例如对于
"1/0"
NameError,例如
"franz/3"
(未定义franz
)TypeError,例如
"[2, 4]/2"
甚至更多。因此,您可能希望捕获所有异常:
实际上,几乎所有现有异常都可以被抛出,并且任何代码的评估都可能造成任何破坏,除非您隔离函数(例如
os. system ("rm -rf /")
,另请参阅Eval 确实很危险)。There are more exceptions possible than SyntaxError only:
ZeroDivisionError, e.g. for
"1/0"
NameError, e.g. for
"franz/3"
(with undefinedfranz
)TypeError, e.g. for
"[2, 4]/2"
and even more. So, you may want to catch them all:
Actually, virtually all existing exceptions can be thrown and any havoc can be wreaked by the evaluation of any code unless you fence out functions (e.g.
os.system ("rm -rf /")
, see also Eval really is dangerous).Eval 通常会引发 SyntaxError,您可以使用 Remember 覆盖您的代码
,您可以隔离
eval
访问任何传递{ '__builtin__': None }
作为第二个参数的函数。Eval usually raises SyntaxError, you can cover your code with
Remember, you can isolate
eval
from accessing any functions passing{ '__builtin__': None }
as second parameter.