Tornado Non-blocking Process

分享一个tornado的non-blocking process方法。
从 tornado-async-process-mixin.py 升级而来,解决了产生僵尸进程的问题,并增加了错误输出的抓取。
使用方法见代码中的示例即可:

class BaseRequestHandler (tornado. web. RequestHandler ):

     '''An non-blocking process
        Example usage:

            class MainHandler(srmlib.BaseRequestHandler):
                @tornado.web.asynchronous
                def get(self):

                    self.call_subprocess('sleep 5; cat /var/run/syslog.pid', self.async_callback(self.on_response))

                def on_response(self, output):
                    self.write(output)
                    self.finish()

        call_subprocess() can take a string command line.
    '''


     def call_subprocess ( self , command , callback = None , io_loop = None , **kargs ):
         self. callback  = callback
         self. io_loop  = io_loop  or tornado. ioloop. IOLoop. instance ( )
         self. process  =  subprocess. Popen (command , shell = True , stdout = subprocess. PIPE , stderr = subprocess. PIPE , **kargs )
         self. pipe  =  self. process. stdout
         self. io_loop. add_handler ( self. pipe. fileno ( ) ,  self._handle_events ,  self. io_loop. READ )

     def _handle_events ( self , fd , events ):
         # Called by IOLoop when there is activity on the pipe output.
         if  self. process. poll ( )  is  not  None:
             self. io_loop. remove_handler (fd )
            output  =  ''. join ( self. pipe )
             self. callback (output )
Posted in Technology Tagged python, tornado

你可能感兴趣的:(Tornado Non-blocking Process)