Search code examples
pythonlinuxstdinbuffering

Python in raw mode stdin print adds spaces


I needed to switch the standard input to non-buffered mode in Python, so that I can read single characters off it. I managed to get it working, but now the standard output is broken: somehow it seems like after the newline character, some space characters are emitted, zero on the first line, 3 on the second, 6 on the third, etc, like this:

ASD
   ASD
      ASD

Operating system is Ubuntu Linux 12.04, 64-bit edition, Python version is 3.2.3.

How can I rid myself from this behavior?

Below is the code I've used:

import sys
import tty
import termios

fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin)

for i in range(0, 10):
    print("ASD")

termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

Solution

  • Looks like you are only doing a line feed but no carriage return. Change your print to

    print("ASD", end="\r\n")