我遇到了以下行为。使用了具有以下结构的代码块,
try:
tup = tuple(<some_expression> for <_> in <iterator>)
except <SomeException>:
pass
当SomeException
在生成元组期间(在生成器表达式中)引发时,try
-except
块没有处理它,而是整个程序停止了。为什么呢?有没有办法确保在genexpr中遇到异常。是否“广播”到外部范围?
具体例子
test.py
:
def input_generator():
try:
while True:
for token in input().split():
yield token
except EOFError:
pass
pyIn = input_generator()
def tuple_gen(n: int):
try:
while True:
yield tuple(next(pyIn) for _ in range(n))
except StopIteration:
pass
except ValueError:
pass
if __name__ == "__main__":
for a, b in tuple_gen(2):
print(a, b)
tuple_gen
考虑使用一个空文件作为输入(as stdin
)迭代生成器的一个实例。遇到 EOF 时,pyIn
生成器终止并因此next(pyIn)
引发StopIteration
,但程序没有被except
块捕获,而是停止。
例如,保存一个空test.txt
文件(只是一个空行)并在(Windows)控制台上运行它
python test.py < test.txt
导致以下回溯:
Traceback (most recent call last):
File "test.py", line 16, in <genexpr>
yield tuple(next(pyIn) for _ in range(n))
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 24, in <module>
for a, b in tuple_gen(2):
File "test.py", line 16, in tuple_gen
yield tuple(next(pyIn) for _ in range(n))
RuntimeError: generator raised StopIteration
更新
正如 timgeb 在评论中指出的那样,这个问题解释了手头的问题。