RosettaCodeData/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py

52 lines
1.3 KiB
Python
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
#!/usr/bin/env python
2017-09-23 10:01:46 +02:00
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
2013-04-10 21:29:02 -07:00
2017-09-23 10:01:46 +02:00
import tty, termios
2016-12-05 22:15:40 +01:00
import sys
if sys.version_info.major < 3:
import thread as _thread
else:
import _thread
2013-04-10 21:29:02 -07:00
import time
try:
2015-02-20 00:35:01 -05:00
from msvcrt import getch # try to import Windows version
2013-04-10 21:29:02 -07:00
except ImportError:
2015-02-20 00:35:01 -05:00
def getch(): # define non-Windows version
2013-04-10 21:29:02 -07:00
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 keypress():
global char
char = getch()
2017-09-23 10:01:46 +02:00
def main():
global char
char = None
_thread.start_new_thread(keypress, ())
while True:
if char is not None:
try:
print("Key pressed is " + char.decode('utf-8'))
except UnicodeDecodeError:
print("character can not be decoded, sorry!")
char = None
_thread.start_new_thread(keypress, ())
if char == 'q' or char == '\x1b': # x1b is ESC
exit()
char = None
print("Program is running")
time.sleep(1)
2013-04-10 21:29:02 -07:00
2017-09-23 10:01:46 +02:00
if __name__ == "__main__":
main()