Package asmach :: Module async

Source Code for Module asmach.async

  1  #! /usr/bin/env python 
  2               
  3  import traceback 
  4  import sys 
  5   
  6  if False: # Set to true to use my implementation 
  7      print "Using Blaise's implementation" 
8 9 - class returnValue:
10 - def __init__(self, value = None):
11 self.value = value 12 raise self
13
14 15 - def function(func):
16 def function_internal(*args, **kwargs): 17 f = func(*args, **kwargs) 18 m = f.send 19 args = (None, ) 20 while True: 21 try: 22 yield_val = m(*args) 23 except StopIteration: 24 raise returnValue(None) 25 else: 26 try: 27 m = f.send 28 if yield_val is None: 29 # We are yielding all the way back. 30 args = yield 31 args = (args, ) 32 else: 33 # f is calling an asynchronous function. 34 m = f.send 35 r = yield_val 36 val = None 37 while True: 38 try: 39 r.send(val) 40 val = yield 41 except returnValue, r: 42 args = (r.value, ) 43 break 44 except: 45 m = f.throw 46 args = list(sys.exc_info()) 47 # Remove misleading lines from the trace. 48 try: 49 args[2] = args[2].tb_next.tb_next 50 except: 51 pass
52 53 return function_internal 54
55 - def start(f):
56 f.next() 57 return f
58 59 @function 70
71 - def run(f, name = "<unnamed>"):
72 try: 73 r = start(print_result(f, name)) 74 while True: 75 r.send(None) 76 except returnValue, r: 77 pass
78 79 else: # Twisted implementation 80 81 from twisted.internet import defer 82 83 function = defer.inlineCallbacks 84 returnValue = defer.returnValue 85 86 #def function(func): 87 # @defer.inlineCallbacks 88 # def exception_grabber(*args, **kwargs): 89 # try: 90 # val = yield defer.inlineCallbacks(func)(*args, **kwargs) 91 # except returnValue: 92 # raise 93 # except: 94 # traceback.print_exc() 95 # raise 96 # returnValue(val) 97 98 # return exception_grabber 99 100 101 @function 106 #except:
107 # print name, "had exception:" 108 # tb = list(sys.exc_info()) 109 # #tb[2] = tb[2].tb_next.tb_next 110 # traceback.print_exception(*tb) 111 112 - def run(f, name = "<unnamed>"):
113 try: 114 r = print_result(f, name) 115 except returnValue, r: 116 pass
117
118 @function 119 -def f(a, b):
120 returnValue(a + b) 121 yield
122
123 @function 124 -def g2():
125 raise Exception("Booh!") 126 yield
127
128 @function 129 -def g(a, b):
130 yield g2() 131 returnValue(5)
132
133 @function 134 -def h(a, b):
135 out = yield (g(a, b)) 136 returnValue(out)
137
138 @function 139 -def i(a, b, c):
140 out = yield (f(a, b)) 141 out2 = f(out, c) 142 out = yield out2 143 returnValue(out)
144
145 -def main():
146 def demo(s): 147 run(eval(s), s)
148 149 demo("f(1,2)") 150 print 151 sys.stdout.flush() 152 demo("g(1,2)") 153 print 154 sys.stdout.flush() 155 demo("h(1,2)") 156 print 157 sys.stdout.flush() 158 demo("i(1,2,3)") 159 sys.stdout.flush() 160 161 if __name__ == "__main__": 162 main() 163 # import trace 164 # tracer = trace.Trace(ignoredirs = [sys.prefix, sys.exec_prefix]) 165 # tracer.run('main()') 166