title: Show curses GUI for a script, even with redirected output
body: <p>I want to write something like a terminal version of dmenu, which can be used to search for a file, and then pass the file's location to another program in the pipeline, like:</p>
  
  <pre class="lang-sh prettyprint-override"><code>my_script | xargs vim # search for a file and open in vim
  </code></pre>
  
  <p>I tried to do it in python with output redirection, but it doesn't seem to work with curses.</p>
  
  <pre class="lang-py prettyprint-override"><code>import sys
  import curses
  
  prev_out = sys.stdout
  print("1:", sys.stdout)
  sys.stdout = open("/dev/tty", "w")
  print("2:", sys.stdout)
  
  window = curses.initscr()
  window.addstr(1, 1, "testing")
  window.getch()
  curses.endwin()
  
  sys.stdout = prev_out
  print("3:", sys.stdout)
  
  </code></pre>
  
  <p>When I call it like this:</p>
  
  <pre class="lang-sh prettyprint-override"><code>myscript &gt; /dev/pts/1 # redirect output to another tty
  </code></pre>
  
  <p>print's behave how I'd expect them to (2 in original tty, 1 and 3 in the other one), but the curses UI is displayed in the /dev/pts/1.<br>
  So my question is, is there a way to redirect curses output back to /dev/tty, or is there a different way to display a text based GUI, which can be redirected by altering sys.stdout?</p>