Python getch + печать из отдельной темы - PullRequest
0 голосов
/ 16 мая 2018

У меня есть программа, которая работает в терминале и ждет нажатия клавиши. Запускаю фоновый поток по инициализации. Я хочу сделать print из фонового потока, но вывод с отступом. Почему выход с отступом? Можно ли сделать так, чтобы он не был отступом?

import sys, termios, tty, time, threading

def getch():
  # Taken from /484486/python-chitaet-odin-simvol-ot-polzovatelya

  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 голосов
/ 17 мая 2018

Это странный взлом, но печать символов возврата на задний план, кажется, решает проблему:

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'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...