0

I have a program that runs in the terminal and waits for a keystroke. I launch a background thread on initialization. I want to do a print from the background thread, but the output is indented. Why is the output indented? Is it possible to make it not be indented?

import sys, termios, tty, time, threading

def getch():
  # Taken from https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user

  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


def do_stuff():
  for i in range(5):
    time.sleep(1)
    print 'test {}'.format(i)

t = threading.Thread(target=do_stuff, args=[], kwargs={})
t.start()


print 'press any key'
print getch()
print 'done'

Output:

press any key
test 0
      test 1
            test 2
                  test 3
                        test 4
                              x
done
Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75

1 Answers1

0

It's a weird hack, but printing backspace characters seems to fix the problem:

import sys, termios, tty, time, threading, random

def getch():
  # Return a single character from stdin.

  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


def do_stuff():
  prev_line = ''
  for i in range(10):
    time.sleep(.5)
    next_line = str(i) * random.randrange(1, 10)
    print '\b' * len(prev_line) + next_line
    prev_line = next_line


t = threading.Thread(target=do_stuff, args=[], kwargs={})
t.start()

print 'press any key'
print getch()
print 'done'
Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75