File: terminal.py

package info (click to toggle)
python-ptrace 0.7-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 680 kB
  • ctags: 1,002
  • sloc: python: 6,659; ansic: 263; makefile: 13; sh: 1
file content (40 lines) | stat: -rw-r--r-- 901 bytes parent folder | download
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
32
33
34
35
36
37
38
39
40
"""
Terminal functions.
"""

from termios import tcgetattr, tcsetattr, ECHO, TCSADRAIN, TIOCGWINSZ
from sys import stdin, stdout
from fcntl import ioctl
from struct import unpack
import os

TERMIO_LFLAGS = 3

def _terminalSize():
    fd = stdout.fileno()
    size = ioctl(fd, TIOCGWINSZ, '1234')
    height, width = unpack('hh', size)
    return (width, height)

def terminalWidth():
    """
    Get the terminal width in characters.
    """
    return _terminalSize()[0]

def enableEchoMode():
    """
    Enable echo mode in the terminal. Return True if the echo mode is set
    correctly, or False if the mode was already set.
    """
    fd = stdin.fileno()
    if not os.isatty(fd):
        return False
    state = tcgetattr(fd)
    if state[TERMIO_LFLAGS] & ECHO:
        return False
    state[TERMIO_LFLAGS] = state[TERMIO_LFLAGS] | ECHO
    tcsetattr(fd, TCSADRAIN, state)
    return True