Part of Slepp's ProjectsPastebinTURLImagebinFilebin
Feedback -- English French German Japanese
Create Upload Newest Tools Donate
Sign In | Create Account

Paste Description for Python process management with C

http://www.defuze.org/archives/198-managing-your-process-with-the-cherrypy-bus.html

Python process management with C
Wednesday, June 9th, 2010 at 2:04:32pm MDT 

  1. # -*- coding: utf-8 -*-
  2. import random
  3. import string
  4. import sys
  5. from multiprocessing import Process, Queue
  6. from Queue import Empty
  7. import logging
  8. from logging import handlers
  9.  
  10. from cherrypy.process import wspbus
  11.  
  12. class MyBus(wspbus.Bus):
  13.     def __init__(self, name=""):
  14.         wspbus.Bus.__init__(self)
  15.         self.open_logger(name)
  16.         self.subscribe("log", self._log)
  17.  
  18.     def exit(self):
  19.         wspbus.Bus.exit(self)
  20.         self.close_logger()
  21.  
  22.     def open_logger(self, name=""):
  23.         logger = logging.getLogger(name)
  24.         logger.setLevel(logging.INFO)
  25.         h = logging.StreamHandler(sys.stdout)
  26.         h.setLevel(logging.INFO)
  27.         h.setFormatter(logging.Formatter("[%(asctime)s] %(name)s - %(levelname)s - %(message)s"))
  28.         logger.addHandler(h)
  29.  
  30.         self.logger = logger
  31.  
  32.     def close_logger(self):
  33.         for handler in self.logger.handlers:
  34.             handler.flush()
  35.             handler.close()
  36.            
  37.     def _log(self, msg="", level=logging.INFO):
  38.         self.logger.log(level, msg)
  39.  
  40.  
  41. class Broker(Process):
  42.     def __init__(self, queue):
  43.         Process.__init__(self)
  44.         self.queue = queue
  45.         self.bus = MyBus(Broker.__name__)
  46.         self.bus.subscribe("main", self.check)
  47.  
  48.     def check(self):
  49.         try:
  50.             message = self.queue.get_nowait()
  51.         except Empty:
  52.             return
  53.        
  54.         if message == "stop":
  55.             self.bus.unsubscribe("main", self.check)
  56.             self.bus.exit()
  57.         elif message.startswith("BUY"):
  58.             self.buy(*message.split(' ', 2)[1:])
  59.         elif message.startswith("SELL"):
  60.             self.sell(*message.split(' ', 2)[1:])
  61.  
  62.     def run(self):
  63.         self.bus.start()
  64.         self.bus.block(interval=0.01)
  65.            
  66.     def stop(self):
  67.         self.queue.put("stop")
  68.  
  69.     def buy(self, code, amount):
  70.         self.bus.log("BUY order placed for %s %s" % (amount, code))
  71.  
  72.     def sell(self, code, amount):
  73.         self.bus.log("SELL order placed for %s %s" % (amount, code))
  74.  
  75. class Bank(object):
  76.     def __init__(self, queue):
  77.         self.bus = MyBus(Bank.__name__)
  78.         self.queue = queue
  79.         self.bus.subscribe("main", self.randomly_place_order)
  80.         self.bus.subscribe("exit", self.terminate)
  81.  
  82.     def randomly_place_order(self):
  83.         order = random.sample(['BUY', 'SELL'], 1)[0]
  84.         code = random.sample(string.ascii_uppercase, 4)
  85.         amount = random.randint(0, 100)
  86.  
  87.         message = "%s %s %d" % (order, ''.join(code), amount)
  88.  
  89.         self.bus.log("Placing order: %s" % message)
  90.        
  91.         self.queue.put(message)
  92.  
  93.     def run(self):
  94.         self.bus.start()
  95.         self.bus.block(interval=0.01)
  96.  
  97.     def terminate(self):
  98.         self.bus.unsubscribe("main", self.randomly_place_order)
  99.         self.bus.unsubscribe("exit", self.terminate)
  100.  
  101.  
  102. if __name__ == '__main__':
  103.     queue = Queue()
  104.    
  105.     broker = Broker(queue)
  106.     broker.start()
  107.  
  108.     bank = Bank(queue)
  109.     bank.run()

Paste Details

advertising

Update the Post

Either update this post and resubmit it with changes, or make a new post.

You may also comment on this post.

update paste below
details of the post (optional)

Note: Only the paste content is required, though the following information can be useful to others.

Save name / title?

(space separated, optional)



Please note that information posted here will expire by default in one month. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.

worth-right