Python Curses: Exiting a program fast
<p>What is the best way to quickly exit a Python program with an infinite loop that uses curses module? </p>

<p>I've tried adding nodelay() method coupled with this at the end of the loop: </p>

<pre><code>if screen.getch() == ord('q'):
    break
</code></pre>

<p>However, it takes 2-3 seconds to make all the function calls on one iteration of the loop. And because of the application, it doesn't make sense to run the loop more often than every 5 second. This means that in order for my way of exiting the program to work, I sometimes have to press and hold 'q' for 2-8 seconds. </p>

<p>My code looks like this:</p>

<pre><code>import curses
import time

def main(screen):
    refresh_rate = 5
    screen.nodelay(1)

    # Infinite loop. Displays information and updates it 
    # every (refresh_rate) # of seconds

    while True:

        # Makes several http requests 
        # and passes responses through multiple functions

        # Escape infinite loop
        if screen.getch() == ord('q'):
            break

        # Wait before going through the loop again
        time.sleep(refresh_rate)

if __name__ == "__main__":
    curses.wrapper(main)
</code></pre>

<p>My other solution was to replace while True with:</p>

<pre><code>loop = 1
while loop:

    #Loop code

if screen.getch() == ord('q'):
    loop = -1
</code></pre>

<p>This way, there is no need to press and hold 'q' to exit the program. But it can still take up to 8 seconds to exit after pressing 'q' once.</p>

<p>For obvious reasons, this doesn't seem to be the best way of exiting the program. I am pretty sure there should be a better (faster) solution.</p>

<p>Other than that, the program works fine. It's 2 files with more than 300 lines, so I am posting just the relevant parts of the code with my attempted solutions.</p>

<p>Given that you have nodelay already, the usual approach is to use napms with a small (20-50 milliseconds) time, and addressing your 5-seconds goal, to run the functions after several (10-25) repetitions of the getch/napms loop.</p>

<p>Mixing curses and standard I/O doesn't really work well unless you take care to flush things when switching between the two.</p>

python ncurses python-curses