Python eval 错误抑制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2140614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:52:49  来源:igfitidea点击:

Python eval error suppression

pythoneval

提问by lamas

First off, I'm aware of eval's disadvantages and it will be used in an experiment I want to make only.

首先,我知道 eval 的缺点,它将用于我只想做的实验。

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

将有很多字符串填充(通常是语法错误的)术语,例如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)
  • 是通过 获得这些术语结果的唯一方法eval吗?
  • 如何让python忽略出现的语法错误eval?(程序不应终止)

回答by Dominic Rodger

To suppress SyntaxError:

压制SyntaxError

try:
    eval("1 + 2) + 3")
except SyntaxError:
    pass

回答by Roberto Rosario

use literal_eval from ast instead and catch ValueError and SyntaxError

改用 ast 中的literal_eval 并捕获ValueError 和SyntaxError

from ast import literal_eval
try:
    a = literal_eval('1+2)+3')
except (ValueError, SyntaxError):
    pass

回答by Stephan Geue

There are more exceptions possible than SyntaxError only:

可能有比 SyntaxError 更多的异常:

  • ZeroDivisionError, e.g. for "1/0"

  • NameError, e.g. for "franz/3"(with undefined franz)

  • TypeError, e.g. for "[2, 4]/2"

  • ZeroDivisionError,例如对于 "1/0"

  • NameError,例如 for "franz/3"(with undefined franz)

  • 类型错误,例如 "[2, 4]/2"

and even more. So, you may want to catch them all:

甚至更多。因此,您可能想将它们全部捕获:

try:
    eval (expr)

except (SyntaxError, NameError, TypeError, ZeroDivisionError):
    pass

Actually, virtually allexisting 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).

实际上,几乎所有现有的异常都可以抛出,并且任何代码的评估都可能造成任何破坏,除非您将函数隔离开来(例如os.system ("rm -rf /"),另请参阅Eval 真的很危险)。

回答by Vestel

Eval usually raises SyntaxError, you can cover your code with

Eval 通常会引发 SyntaxError,你可以用

try:
  a = eval('1+2)+3')
except SyntaxError:
  pass

Remember, you can isolate evalfrom accessing any functions passing { '__builtin__': None }as second parameter.

请记住,您可以隔离eval访问{ '__builtin__': None }作为第二个参数传递的任何函数。