【发布时间】:2012-12-14 09:38:04
【问题描述】:
我遇到了一种情况,我需要在我的 try/except 代码中确定哪个嵌套生成器引发了 StopIteration 异常。我该怎么做?以下是一个虚拟示例:
def genOne(iMax, jMax):
i = 0;
g2 = genTwo(jMax)
while i <= iMax:
print('genOne: ' + str(i))
next(g2)
yield
i = i + 1
def genTwo(jMax):
j = 0;
while j <= jMax:
print('genTwo: ' + str(j))
yield
j = j + 1
g1 = genOne(6, 3) # The inputs are arbitrary numbers
try:
while True:
next(g1)
except:
# Do some processing depending on who generates the StopIteration exception
谢谢!
【问题讨论】:
-
为什么不让
genOne处理异常? -
在真正的问题中,我无法访问生成器。假设生成器不能修改,我可以轻松确定吗?
标签: python-3.x