back to Index
a simple python method-execution kernel
In [1]:
# Cross-notebook include shim
with open("nbinclude.ipynb") as nbinclude_f: # don't rename nbinclude_f
import IPython.nbformat.current
get_ipython().run_cell(IPython.nbformat.current.read(nbinclude_f, 'json').worksheets[0].cells[0].input)
In [60]:
import time
class SimpleKernel:
def __init__(self):
self.running=False
self.coroutines=[]
def add_coroutine(self, coroutine, period):
self.coroutines.append([coroutine, period, time.time()])
def tick(self):
running = True
for cr in self.coroutines:
now=time.time()
if (now - cr[2]) > cr[1]:
# cr[0].next()
# try:
result= next(cr[0])
if result is not None:
running = running and result
# except StopIteration as i:
# print(i)
# print("stopiteration caught" + str(i.message) + str(cr[0]))
# pass
cr[2]=now
return running
def run(self):
try:
self.running=True
while self.running:
self.running = self.tick()
# time.sleep(.001)
except KeyboardInterrupt as e:
print("caught keyboardinterrupt")
print(e)
In [1]:
class CoroutineSpinner:
def __init__(self, coroutine):
self.coroutine=coroutine
self.running=False
def run(self):
self.running=True
while(self.running):
delay=next(self.coroutine)
if delay < 0:
return
time.sleep(delay)
In [3]:
#NBINCLUDE_STOP
In [33]:
def counter(name):
i = 0;
while True:
i+=1
print name, i
sys.stdout.flush()
yield
In [34]:
c=counter('hello')
In [35]:
c.next()
In [36]:
c2=counter('----->')
In [37]:
c2.next()
In [38]:
sk=SimpleKernel()
In [39]:
sk.add_coroutine(c, .25)
In [40]:
sk.add_coroutine(c2, 1)
In [58]:
sk.tick()
In [43]:
sk.run()
In [ ]:
import time
class ThreadedScheduler:
def __init__(self):
self.running=False
self.coroutines=[]
def add_coroutine(self, coroutine, period):
self.coroutines.append([coroutine, period, time.time()])
def tick(self):
running = True
for cr in self.coroutines:
now=time.time()
if (now - cr[2]) > cr[1]:
# cr[0].next()
# try:
result= next(cr[0])
if result is not None:
running = running and result
# except StopIteration as i:
# print(i)
# print("stopiteration caught" + str(i.message) + str(cr[0]))
# pass
cr[2]=now
return running
def run(self):
try:
self.running=True
while self.running:
self.running = self.tick()
# time.sleep(.001)
except KeyboardInterrupt as e:
print("caught keyboardinterrupt")
print(e)
In [ ]: