How to take input from stdin, display something using curses and output to stdout?
<p>I'm trying to make a python script that takes input from stdin, displays GUI in terminal using curses and then when user finishes interaction outputs the result to the stdout. Good example of this behaviour is <a href="https://github.com/garybernhardt/selecta" rel="nofollow">selecta</a> but it's written in ruby.</p>

<p>I can't make curses display anything. This is minimal (it only displays one character and waits for one character) example of what I tried so far:</p>

<pre><code>import os, sys
import curses

c = None

old_out = sys.__stdout__
old_in = sys.__stdin__
old_err = sys.__stderr__
sys.__stdout__ = sys.stdout = open('/dev/tty', 'w')
sys.__stdin__ = sys.stdin = open('/dev/tty')
sys.__stderr__ = sys.stderr = open('/dev/tty')


def show_a(s):
    global c
    s.addch(ord('a'))
    c = s.getch()

curses.wrapper(show_a)

sys.stdin.flush()
sys.stdout.flush()
sys.stderr.flush()
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
sys.__stdout__ = sys.stdout = old_out
sys.__stdin__ = sys.stdin = old_in
sys.__stderr__ = sys.stderr = old_err

print(c)
</code></pre>

<p>When I try to use <code>echo $(python3 show_a.py)</code> nothing is displayed but after pressing any key its number is displayed:</p>

<p><a href="http://i.stack.imgur.com/lOsvS.png" rel="nofollow"><img src="http://i.stack.imgur.com/lOsvS.png" alt="curses displays nothing in terminal"></a></p>

<p>Is something like this even possible using curses, if so how to do this?</p>

<p>It doesn't work because the <code>print</code> statement is writing to the same standard output as <a href="https://docs.python.org/2/library/curses.html#curses.wrapper" rel="nofollow"><code>curses.wrapper</code></a>.  You can either defer that <code>print</code> until after you have restored <code>sys.stdout</code>, or you could use the <code>file=</code> property something like this:</p>

<pre><code>printf(s.getch(), file=old_out)
</code></pre>

<p>For the other (ordering) problem, it sounds as if you need to amend the code to do a <a href="https://docs.python.org/2/library/curses.html#curses.window.refresh" rel="nofollow"><em>refresh</em></a> after the <code>getch</code> (to make curses display it), and depending on what version of curses, a <em>flush</em> of the standard output would then be helpful.</p>

<p>Further reading:</p>

<ul>
<li><a href="http://stackoverflow.com/questions/6796492/temporarily-redirect-stdout-stderr">Temporarily Redirect stdout/stderr</a></li>
</ul>

python curses python-curses