-1

I'm trying to add code to exit my curses python script correctly when the user types q. I can't merely do CTRL+C because then curses won't be de-initialized correctly.

I haven't found a good solution with getting user input that has a timeout so the program doesn't sit there until the user gives some input.

Is there a simple way with creating a second thread that just handles user input and can request the main thread to run a de-init function?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
minnymauer
  • 374
  • 1
  • 4
  • 17
  • 2
    See here http://stackoverflow.com/questions/24308583/python3-curses-how-to-press-q-for-ending-program-immediately – Paul Rooney Jul 31 '16 at 23:47

1 Answers1

2

The suggested answer Python3 + Curses: How to press “q” for ending program immediately? is a starting point, but (like the suggestion for using a separate thread) is not what is needed.

Here is an example, starting from the former:

import sys, curses, time

def main(sc):
    sc.nodelay(1)

    while True:
        try:
            sc.addstr(1, 1, time.strftime("%H:%M:%S"))
            sc.refresh()

            if sc.getch() == ord('q'):
                break

            time.sleep(1)
        except KeyboardInterrupt:
            curses.endwin()
            print "Bye"
            sys.exit()

if __name__=='__main__': curses.wrapper(main)

When you press ^C, it sends a keyboard interrupt. If you catch that, you can tell curses to cleanup (and restore the terminal modes). After that, exit.

A separate thread will not work because it is unlikely that the underlying curses is thread-safe (and improbable that someone has gotten around to using the feature from Python).

Further reading:

Community
  • 1
  • 1
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105