Tornado Non-blocking Process

来源:互联网 发布:卫星免费网络电视直播 编辑:程序博客网 时间:2024/05/21 06:45

分享一个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 TechnologyTagged python, tornado
原创粉丝点击