| 1 |
""" |
| 2 |
Terminal functions. |
| 3 |
""" |
| 4 |
|
| 5 |
from termios import tcgetattr, tcsetattr, ECHO, TCSADRAIN, TIOCGWINSZ |
| 6 |
from sys import stdin, stdout |
| 7 |
from fcntl import ioctl |
| 8 |
from struct import unpack |
| 9 |
import os |
| 10 |
|
| 11 |
TERMIO_LFLAGS = 3 |
| 12 |
|
| 13 |
|
| 14 |
def _terminalSize(): |
| 15 |
fd = stdout.fileno() |
| 16 |
size = ioctl(fd, TIOCGWINSZ, '1234') |
| 17 |
height, width = unpack('hh', size) |
| 18 |
return (width, height) |
| 19 |
|
| 20 |
|
| 21 |
def terminalWidth(): |
| 22 |
""" |
| 23 |
Get the terminal width in characters. |
| 24 |
""" |
| 25 |
return _terminalSize()[0] |
| 26 |
|
| 27 |
|
| 28 |
def enableEchoMode(): |
| 29 |
""" |
| 30 |
Enable echo mode in the terminal. Return True if the echo mode is set |
| 31 |
correctly, or False if the mode was already set. |
| 32 |
""" |
| 33 |
fd = stdin.fileno() |
| 34 |
if not os.isatty(fd): |
| 35 |
return False |
| 36 |
state = tcgetattr(fd) |
| 37 |
if state[TERMIO_LFLAGS] & ECHO: |
| 38 |
return False |
| 39 |
state[TERMIO_LFLAGS] = state[TERMIO_LFLAGS] | ECHO |
| 40 |
tcsetattr(fd, TCSADRAIN, state) |
| 41 |
return True |