在"yield from"后使用try-except语句来捕获StopIteration异常并处理它。
示例代码如下:
def subgen():
while True:
received = yield
# do something with received
def main():
subgen_instance = subgen()
next(subgen_instance)
try:
yield from subgen_instance
except StopIteration:
# handling StopIteration here
pass
在这个示例中,启动子生成器subgen()的实例subgen_instance并立即调用next(subgen_instance)调用了其内部yield语句。在调用主生成器的yield from子生成器之后,我们将用try-except语句来捕获并处理Python自动提出的StopIteration异常,因为此时没有更多的生成器输出。该处理包括yield from语句的结束处理。在这种情况下,我们只是简单地传递了控制,但是在实际应用中,可能需要更多的期望行为。