Simple loop 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def inside(name):
for x in range(5):
print(name,':',x)
yield
def broken():
print('Begin broken')
yield inside('broken')
print('End broken')
def ok():
print('Begin ok')
yield from inside('ok')
print('End ok')
class Eventloop:
coroutines = []
def run(self):
while True:
if len(self.coroutines) == 0:
break
for coro in self.coroutines:
try:
next(coro)
except StopIteration as e:
print(coro, 'is end.')
self.coroutines.remove(coro)
def add_coroutine(self, coro):
self.coroutines.append(coro())
loop = Eventloop()
loop.add_coroutine(broken)
loop.add_coroutine(ok)
if __name__ == '__main__':
loop.run()
Begin broken
Begin ok
ok : 0
End broken
<generator object broken at 0x7f30bf3068e0> is end.
ok : 1
ok : 2
ok : 3
ok : 4
End ok
<generator object ok at 0x7f30bf306990> is end.