Chinaunix

标题: 得到terminal下的width [打印本页]

作者: stlaw    时间: 2009-03-04 18:05
标题: 得到terminal下的width
这条thread挺有用的:
http://mail.python.org/pipermail/python-list/2000-May/033564.html
之前只知道用curses模块,windows下面还要安装wcurses,这个1调用就跑出1窗口。
整理下, for linux(windows除了wcurses 不知道):
1. curses
win = curses.initscr()
w = win.getmaxyx()[1]
curses.endwin()
2. 命令 stty -a, 得到的columns
# stty -a  speed 38400 baud; rows 58; columns 132; line = 0;intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = ; eol2 = ; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbelopost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
stty size 得到的1对值(rows, columns)
# stty  size58 132
3. 命令 tput cols
# tput cols132
4. 1个可用于多数unix的用法:
def getTerminalSize():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            cr = (25, 80)
    return int(cr[1]), int(cr[0])
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/57278/showart_1851397.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2