title: asynchronous subprocess using flask-aiohttp
body: <p>I'm using a <a href="http://flask.pocoo.org/" rel="noreferrer"><code>Flask</code></a> web server to provide an interface to a time-consuming calculation. To increase performance, I want to</p>
  
  <ol>
  <li>start the calculation as a <a href="https://docs.python.org/3.4/library/asyncio-subprocess.html" rel="noreferrer">new subprocess</a> to be able to use multiple CPU cores for multiple concurrent calculations</li>
  <li>let the calculations run asynchronously using <a href="https://docs.python.org/3.4/library/asyncio.html" rel="noreferrer"><code>asyncio</code></a></li>
  </ol>
  
  <p>To call <code>asyncio</code> coroutines from Flask I started using <a href="http://flask-aiohttp.readthedocs.org/en/latest/coroutine.html" rel="noreferrer"><code>flask-aiohttp</code></a>, which is working nicely for simple delay tasks as shown in the examples.
  However, I fail to call the asynchronous subprocess from inside Flask:</p>
  
  <pre><code>#!/usr/bin/env python3
  # coding: utf-8
  
  from flask import Flask
  from flask.ext.aiohttp import AioHTTP, async
  
  import asyncio
  from asyncio.subprocess import PIPE
  
  CALC_SCRIPT = './calc'
  
  app = Flask(__name__)
  aio = AioHTTP(app)
  
  @app.route('/calc/&lt;int:n&gt;')
  @async
  def calc(n):
      print('calc({}) called'.format(n))
      create = asyncio.create_subprocess_exec(CALC_SCRIPT, str(n),
                                              stdout=PIPE, stderr=PIPE)
      print('create... ', end='')
      process = yield from create
      print('process created. {!r}, type={}'.format(process,
                                                    type(process)))
      yield from process.wait()
      print('process finished.')
  
      # yields (stdout, stderr)
      result = '\n'.join(ch.decode().rstrip() for ch in
                          (yield from process.communicate()) if ch)
      return result
  
  if __name__ == '__main__':
      aio.run(app, debug=True)
  </code></pre>
  
  <p>The process is being created, but never returns:</p>
  
  <pre><code>GET http://127.0.0.1:5000/calc/5
  calc(5) called
  creating... process created. &lt;Process 5647&gt;,
      type=&lt;class 'asyncio.subprocess.Process'&gt;
  </code></pre>
  
  <p>What am I doing wrong?</p>