Home

Tags

python, прерывание цикла по нажатию клавиши (linux)

2012-01-05 python linux

Пример прерывания цикла по нажатию клавиши, проверено на python 2.7 + linux.

# coding: utf8

import sys, select, termios

def kbhit():
    r = select.select([sys.stdin], [], [], 0)
    return bool(r[0])

if __name__ == '__main__':
    fd = sys.stdin.fileno()
    old_term = termios.tcgetattr(fd)
    new_term = termios.tcgetattr(fd)
    new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)

    try:
        termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)

        while 1:
            if kbhit():
                ch = sys.stdin.read(1)
                break
            sys.stdout.write('.')

        print 'done'
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)