Skip to content

Instantly share code, notes, and snippets.

@icsaas
Created March 18, 2014 06:47
Show Gist options
  • Save icsaas/9614772 to your computer and use it in GitHub Desktop.
Save icsaas/9614772 to your computer and use it in GitHub Desktop.
nonblocking process in tornado
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