summaryrefslogtreecommitdiff
path: root/keyboardpython/__init__.py
blob: 216f08d5826dc9fa01468af1fb5307c6a1ad04fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import key

def set_to_read_key(fd='default'):
    ''' Set tty so that os.read gets one keypress at a time '''
    import sys,termios
    if fd == 'default': fd = sys.stdin.fileno()
    global before_tty
    before_tty = termios.tcgetattr(fd)
    tty = termios.tcgetattr(fd)
    tty[3] = tty[3] & ~termios.ICANON & ~termios.ECHO
    tty[6][termios.VMIN] = 1
    tty[6][termios.VTIME] = 0
    termios.tcsetattr(fd, termios.TCSANOW, tty)

def reset_tty(fd='default'):
    ''' set tty to how it was before set_to_read_key '''
    import sys,termios
    if fd == 'default': fd = sys.stdin.fileno()
    termios.tcsetattr(fd, termios.TCSANOW, before_tty)

def getkey(fd='default',buffersize=6):
    ''' Read keypress and return Key object.

        - fd='default' will try and get this stdin.
        - buffersize is passed to os.read, 6 is 
        enough for alt+F12 for example.
    '''
    import os,sys
    if fd == 'default': fd = sys.stdin.fileno()
    c = os.read(fd,buffersize)
    return key.parse_code(c)