1

I have a very weird print() bug while using Threads and Termios. I have a repeating Thread catching a key via Termios while printing some stuff. But always it prints a new line it doesn't start at the beginning of the line but where the last line ended.

This is my code:

def func1():
    while True:
        try:
            var = int(inputChar())
        except ValueError:
            var = 0

Thread(target=func1).start()
while True:
    print("stuff")
    time.sleep(2)

This is my inputChar() function:

import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
    tty.setraw(sys.stdin.fileno())
    ch = sys.stdin.read(1)
finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

This ist the expected output:

stuff
stuff
stuff
stuff
stuff

This is the output:

stuff
stuff
     stuff
          stuff
               stuff
Noxmain
  • 13
  • 2
  • It looks like your prints end with a linefeed but not a newline. – John Gordon Jan 16 '20 at 16:53
  • 1
    Looks like a race condition; the output probably depends on whether `print` is called between the calls to `tty.setraw` and `terms.tcsetattr` in the other thread. – chepner Jan 16 '20 at 16:57

1 Answers1

2

I have no idea why this is happening but you can fix it by replacing the print command with

print("stuff\r")

or

sys.stdout.write("stuff\n\r")

the \r at the end is known as a cartridge return. It's useful when sys.stdout.write() is not a viable option

I_bad_at_code
  • 64
  • 1
  • 7