pythonpython-curses

Python: Curses not showing printed text untill getkey() is called


I have a python code that prints to the screen some text. But if i omit the stdsrc.getkey() function nothing prints to the screen.

import curses

def write(stdscr):

    stdscr.clear()
    stdscr.refresh()

    stdscr.addstr("this is a test string")
    stdscr.refresh()

def main():
    curses.wrapper(write)

if __name__ == '__main__':
    main()

the above code does not show any thing on the screen but if i modify it as shown below it prints the "this is a test string" to the terminal

import curses

def write(stdscr):

    stdscr.clear()
    stdscr.refresh()

    stdscr.addstr("this is a test string")
    stdscr.refresh()
    stdscr.getkey()

def main():
    curses.wrapper(write)

if __name__ == '__main__':
    main()

Solution

  • You are using curses.wrapper which resets the terminal window once write exits. Without getkey it exists very quickly, the window is reset and you see nothing. getkey causes write to wait for a key and so you have time to see the change in the window. If you put time.sleep(5) instead of getkey you will have a similar effect. If you don't use wrapper, but call write directly, you will also see a change to the window.