Search code examples
pythoncurses

Python curses reading a single character from stdin affects output from print statement


I'm trying to do a non-blocking read of a single character from stdin. I have found a solution with the curses library, but I'm doing something wrong when trying to write output back to stdout.

import curses
from time import sleep

def callback(screen):
  screen.nodelay(1)
  return screen.getkey()

while 1:
  try:
    key = curses.wrapper(callback)
    print "Got keypress: ", key
  except:
    sleep(3)
    print "No Keypress"
    print "Program\nOutput"

# Prints
No Keypress
          Program
                  Output

Everything works flawlessly with the exception of the indented output. Is there any way to fix this?


Solution

  • It would appear that using curses, '\n' is just a form feed. You presumably need to output a carriage return as well, or else explicitly use curses to reposiition the cursor.