title: How to execute shell command and stream output with Python and Flask upon HTTP request?
body: <p>Following <a href="https://stackoverflow.com/questions/15092961/how-to-continuously-display-python-output-in-a-webpage">this post</a>, I am able to <code>tail -f</code> a log file to a webpage:</p>
  
  <pre><code>from gevent import sleep
  from gevent.wsgi import WSGIServer
  import flask
  import subprocess
  
  app = flask.Flask(__name__)
  
  @app.route('/yield')
  def index():
      def inner():
          proc = subprocess.Popen(
                  ['tail -f ./log'],
                  shell=True,
                  stdout=subprocess.PIPE
                  )
          for line in iter(proc.stdout.readline,''):
              sleep(0.1)
              yield line.rstrip() + '&lt;br/&gt;\n'
  
      return flask.Response(inner(), mimetype='text/html')
  
  http_server = WSGIServer(('', 5000), app)
  http_server.serve_forever()
  </code></pre>
  
  <p>There are two issues in this approach.</p>
  
  <ol>
  <li>The <code>tail -f log</code> process will linger after closing the webpage. There will be n tail process after visiting <a href="http://localhost:5000/yield" rel="nofollow noreferrer">http://localhost:5000/yield</a> n time</li>
  <li>There can only be 1 client accessing <a href="http://localhost:5000/yield" rel="nofollow noreferrer">http://localhost:5000/yield</a> at a single time</li>
  </ol>
  
  <p>My question(s) is, is it possible to make flask execute a shell command when someone visit a page and terminating the command when client close the page? Like <kbd>Ctrl</kbd>+<kbd>C</kbd> after <code>tail -f log</code>. If not, what are the alternatives?
  Why was I only able to have 1 client accessing the page at a time?</p>
  
  <p>Note: I am looking into general way of starting/stoping an arbitrary shell command instead of particularly tailing a file</p>