Created
March 18, 2014 06:47
-
-
Save icsaas/9614772 to your computer and use it in GitHub Desktop.
nonblocking process in tornado
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment