Python中的SyntaxError不一致? [英] SyntaxError inconsistency in Python?
问题描述
考虑这两个片段:
try:
a + a = a
except SyntaxError:
打印第一个异常捕获
。
try:
eval(a + a = a)
除了SyntaxError:
打印第二个异常被捕获
在第二种情况下,第二个异常..语句被打印(异常捕获),而在第一个不是。
是第一个异常(可以称之为SyntaxError1)与第二个异常(SyntaxError2)有什么不同?
<有没有办法捕获SyntaxError1(从而抑制编译时错误)?在
eval
中包装大块代码是不能令人满意的;)第一种情况是编译器提出的例外是在 之前运行 (因为编译器本身将在解析之后立即进行设置)。在第二种情况下,编译器运行两次 - 当编译器作为 c 之后的 eval 的一部分运行时,异常就会被引发编译器的运行已经设置了
try / except
。
因此,为了截取语法错误,单向或者另一个,你必须安排编译器运行两次 - eval
是一种方式,显式编译
在函数中调用另一个, import
非常方便(在将代码写入另一个文件之后), exec
和 execfile
其他可能性。但是,无论如何,只有在编译器首次运行设置 try / except
块之后才能捕获语法错误!
Consider these two snippets:
try:
a+a=a
except SyntaxError:
print "first exception caught"
.
try:
eval("a+a=a")
except SyntaxError:
print "second exception caught"
In the second case the "second exception .." statement is printed (exception caught), while in the first one isn't.
Is first exception (lets call it "SyntaxError1") any different from second one ("SyntaxError2")?
Is there any way to catch SyntaxError1 (thus supressing compilation-time errors)? Wrapping large blocks of code in eval
is unsatisfactory ;)
In the first case, the exception is raised by the compiler, which is running before the try/except
structure even exists (since it's the compiler itself that will set it up right after parsing). In the second case, the compiler is running twice -- and the exception is getting raised when the compiler runs as part of eval
, after the first run of the compiler has already set up the try/except
.
So, to intercept syntax errors, one way or another, you have to arrange for the compiler to run twice -- eval
is one way, explicit compile
built-in function calls another, import
is quite handy (after writing the code to another file), exec
and execfile
other possibilities yet. But however you do it, syntax errors can be caught only after the compiler has run one first time to set up the try/except
blocks you need!
这篇关于Python中的SyntaxError不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!