使用import console
(width, height) = console.getTerminalSize()
print "Your terminal's width is: %d" % width
编辑:噢,对不起。这不是python标准的lib库,这里是console.py的源代码(我不知道它来自哪里)。
这个模块似乎是这样工作的:当是的时候,它检查termcap是否可用。它使用它;如果没有,它检查终端是否支持一个特殊的ioctl调用,并且这个调用也不起作用,它检查一些shell为此导出的环境变量。
这可能只适用于UNIX。def getTerminalSize():
import os
env = os.environ
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
'1234'))
except:
return
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:
cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
### Use get(key[, default]) instead of a try/catch
#try:
# cr = (env['LINES'], env['COLUMNS'])
#except:
# cr = (25, 80)
return int(cr[1]), int(cr[0])