Advertisement
Guest User

Untitled

a guest
Jun 5th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.12 KB | None | 0 0
  1. """
  2. Simulate an asyncio based "web" server with a GameInstance that needs
  3. an input queue.
  4.  
  5. GameInstance in this case is a class that takes input commands from a
  6. queue. Some commands are fast, and some are slow. The results of the commands
  7. are written to an output queue.
  8. """
  9. import asyncio
  10. import sys
  11. import time
  12.  
  13. if sys.version_info < (3,5):
  14.     assert False, "Bad python version %s" % sys.version_info
  15. else:
  16.     print("Running python:", sys.version_info)
  17.  
  18. Input_queue = asyncio.Queue()
  19. Output_queue = asyncio.Queue()
  20.  
  21. DELAY = time.sleep
  22.  
  23. async def queue_monitor():
  24.     global Input_queue, Output_queue
  25.  
  26.     while True:
  27.         await asyncio.sleep(5)
  28.         ol = Output_queue.qsize()
  29.         il = Input_queue.qsize()
  30.         print("QM: Input queue: %d, Output queue: %d" % (il, ol))
  31.  
  32.  
  33. async def queue_eater():
  34.     global Input_queue
  35.     while True:
  36.         inp = await Input_queue.get()
  37.         print("EAT:", inp)
  38.  
  39. class GameInstance:
  40.     def __init__(self):
  41.         self.vars = {}
  42.  
  43.     def get_var(self, name):
  44.         if name not in 'abcd':
  45.             raise ValueError("Variable name out of range: '%s'" % name)
  46.  
  47.         value = self.vars.get(name, 0)
  48.         return value
  49.  
  50.     @staticmethod
  51.     async def take_input():
  52.         global Input_queue
  53.         instr = await Input_queue.get()
  54.         print("GI: Taking input: %s" % instr)
  55.         return instr
  56.  
  57.     def op(self, op1, oper, op2):
  58.         val1 = int(op1) if op1.isdigit() else self.get_var(op1)
  59.         val2 = int(op2) if op2.isdigit() else self.get_var(op2)
  60.  
  61.         print("GI: Doing fast operation: %s %s %s" % (op1, oper, op2))
  62.  
  63.         result = {
  64.             '+': (lambda a,b: a+b),
  65.             '-': (lambda a,b: a-b),
  66.             '*': (lambda a,b: a*b),
  67.             '/': (lambda a,b: a//b),
  68.         }[oper](val1, val2)
  69.  
  70.         print("GI: Result =", result)
  71.  
  72.     def opassign(self, op1, oper, op2):
  73.         val1 = self.get_var(op1)
  74.         val2 = int(op2) if op2.isdigit() else self.get_var(op2)
  75.  
  76.         print("GI: Starting slow operation: %s %s %s" % (op1, oper, op2))
  77.  
  78.         opfunc = {
  79.             '=': (lambda a,b: b),
  80.             '+=': (lambda a,b: a+b),
  81.             '-=': (lambda a,b: a-b),
  82.             '*=': (lambda a,b: a*b),
  83.             '/=': (lambda a,b: a//b),
  84.         }
  85.         result = opfunc[oper](val1, val2)
  86.  
  87.         self.vars[op1] = result
  88.         time.sleep(2)
  89.         print("GI: Result =", result)
  90.  
  91.     def process_input(self, step):
  92.         try:
  93.             opd1, oper, opd2 = step.split()
  94.             print("GI: process", (opd1, oper, opd2))
  95.             if oper in ('=', '+=', '-=', '*=', '/='):
  96.                 self.opassign(opd1, oper, opd2)
  97.             else:
  98.                 self.op(opd1, oper, opd2)
  99.         except Exception as ex:
  100.             print("GI: Input error. Could not parse: %s" % step)
  101.             print("... exception:", ex)
  102.  
  103.         Input_queue.task_done()
  104.  
  105.     async def run(self):
  106.         while True:
  107.             # Give other coroutines a chance to run
  108.             await asyncio.sleep(0)
  109.             # block on queue
  110.             step = await self.take_input()
  111.             print("GI: run has input %s" % step)
  112.             self.process_input(step)
  113.  
  114. class WebsocketPool():
  115.     """Get inputs, put them in input queue."""
  116.     def __init__(self, loop):
  117.         self.loop = loop
  118.         loop.add_reader(sys.stdin, WebsocketPool.handle_input)
  119.         print("WSP: Added reader for stdin")
  120.  
  121.     @staticmethod
  122.     def handle_input():
  123.         print("WSP: handle_input called")
  124.         inp = sys.stdin.readline().strip()
  125.         print("WSP: Got input: %s" % inp)
  126.         asyncio.async(Input_queue.put(inp))
  127.         print("WSP: Added to input queue")
  128.  
  129.  
  130. def main():
  131.     game = GameInstance()
  132.  
  133.     loop = asyncio.get_event_loop()
  134.     loop.set_debug(enabled=True)
  135.  
  136.     wsp = WebsocketPool(loop)
  137.     print("MAIN: Created WebsocketPool")
  138.  
  139.     loop.create_task(queue_monitor())
  140.     print("MAIN: Created queue_monitor task")
  141.  
  142.     #loop.create_task(queue_eater())
  143.     loop.create_task(game.run())
  144.     print("MAIN: Created game.run task")
  145.  
  146.     try:
  147.         loop.run_forever()
  148.     except KeyboardInterrupt:
  149.         print("MAIN: Terminated from keyboard")
  150.     finally:
  151.         loop.close()
  152.  
  153.  
  154.  
  155. if __name__ == '__main__':
  156.     exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement