title: redirect sys.stdout to specific Jupyter Notebook cell
body: <p>Jupyter==4.1.0, Python==2.7.10, IPython==4.2.0</p>
  <p>I'm writing a SQL UI for my Jupyter Notebooks and would like to incorporate multithreading so that I can run a query in one cell and continue to work in other cells while the query is running.</p>
  <p>The problem I'm having is that if I execute a query in one cell, the output will be displayed in the last-executed cell's output prompt instead of in the output prompt of the cell that executed the query.</p>
  <p>I scoured the interwebs and discovered <a href="https://stackoverflow.com/questions/14393989/per-cell-output-for-threaded-ipython-notebooks">this clever trick</a>, but I think it's outdated and/or no longer works in my version of Jupyter. When I run it, I only get output for whatever cell was last executed. So if I run both, I only get the last-executed output, instead of the output printing to separate cells simultaneously.</p>
  <p>So I have my context manager which sets the <code>parent_header</code>:</p>
  <pre><code>import sys
  import threading
  from contextlib import contextmanager
  
  # we need a lock so that other threads don't snatch control
  # while we have set a temporary parent
  stdout_lock = threading.Lock()
  
  @contextmanager
  def set_stdout_parent(parent):
      &quot;&quot;&quot;a context manager for setting a particular parent for sys.stdout 
      the parent determines the destination cell of the output
      &quot;&quot;&quot;
      save_parent = sys.stdout.parent_header
      with stdout_lock:
          sys.stdout.parent_header = parent
          try:
              yield
          finally:
              # the flush is important, because that's when the parent_header actually has its effect
              sys.stdout.flush()
              sys.stdout.parent_header = save_parent
  </code></pre>
  <p>I essentially want to be able to get the <code>parent_header</code> of a cell In[1] and redirect the output of cell In[2] to the output of In[1].</p>
  <p>Example:</p>
  <p>Get <code>parent_header</code> of In[1]:</p>
  <pre><code>In[1]: t = sys.stdout.parent_header
  </code></pre>
  <p>Then the following code will run, but the output should print to Out[1] (currently, I get no output when I run this code):</p>
  <pre><code>In [2]: with set_stdout_parent(t):
              print 'FOO'
  </code></pre>
  <p>Which should produce:</p>
  <pre><code>In[1]: t = sys.stdout.parent_header
  Out[1]:'FOO'
  </code></pre>