Python getch +打印来自单独的线程

时间:2018-05-16 20:49:00

标签: python multithreading io

我有一个在终端中运行的程序,等待击键。我在初始化时启动后台线程。我想从后台线程中执行print,但输出是缩进的。为什么输出缩进?是否有可能使其不缩进?

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'

输出:

press any key
test 0
      test 1
            test 2
                  test 3
                        test 4
                              x
done

1 个答案:

答案 0 :(得分:0)

这是一个奇怪的黑客,但打印退格字符似乎解决了这个问题:

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'