Portál AbcLinuxu, 30. dubna 2025 15:26
initscr()
import curses curses.setupterm() curses.tigetnum("lines"), curses.tigetnum("cols")
import sys, os, fcntl, termios, array winsBuff = array.array("H", (0,0,0,0)) def getTermSize(): """ Find out terminal size """ if os.isatty(sys.stdout.fileno()): fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, winsBuff, True) return winsBuff[0], winsBuff[1] return 0, 0Na čísla se dá spolehnout dokud nedorazí signál SIGWINCH, pak je potřeba měřit znovu. Konstrukce pole
winsBuff
počítá s tím, že velikost libc struktury winsize
je 4x short int, a nevsadil bych ruku, že to platí na všech platformách. Vlastně bych nevsadil ani suchar, možná bude lepší ten prstíček ohřát…
Tiskni
Sdílej:
#define SCR_WID_FALLBACK 80
int Shell::screen_width()
{
int fd;
struct winsize wsz;
fd = fileno(stdout);
if (ioctl (fd, TIOCGWINSZ, &wsz) < 0)
return SCR_WID_FALLBACK;
return wsz.ws_col;
}
struktura winsize je (u mně) definována takhle:
struct winsize
{
unsigned short int ws_row;
unsigned short int ws_col;
unsigned short int ws_xpixel;
unsigned short int ws_ypixel;
};
A protože okolo ní nejsou žádný #ifdefy apod., nemuselo by to snad s platform-dependencí být tak hrozné...def get_terminal_width_termios(): try: import fcntl, termios except ImportError: return None s = struct.pack("HHHH", 0, 0, 0, 0) try: lines, cols, xpixels, ypixels = \ struct.unpack( "HHHH", fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s) ) except (IOError, AttributeError): return None return cols def get_terminal_width_resize(): c = commands.getoutput('resize').split('\n') c = [x for x in c if x.startswith('COLUMNS=')] if c: c = c[0] dummy, c = c.split('=', 1) if c[-1] == ';': c = c[:-1] if c: return int(c) else: return None def get_terminal_width_dumb(): return 80 def get_terminal_width(): handlers = [get_terminal_width_termios, get_terminal_width_resize, get_terminal_width_dumb] for handler in handlers: width = handler() if width is not None: return width return 80 # fallback, should not happen
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.