在python中是否有一种方法以编程方式确定控制台的宽度?我指的是一行中不换行的字符数,而不是窗口的像素宽度。
Edit
寻找在Linux上工作的解决方案
在python中是否有一种方法以编程方式确定控制台的宽度?我指的是一行中不换行的字符数,而不是窗口的像素宽度。
Edit
寻找在Linux上工作的解决方案
当前回答
试着“祝福”
我也在找同样的东西。它非常易于使用,并提供了在终端中着色、造型和定位的工具。你需要的很简单:
from blessings import Terminal
t = Terminal()
w = t.width
h = t.height
在Linux中工作就像一个魅力。(我不确定MacOSX和Windows)
在此下载及文件
或者你可以用pip安装它:
pip install blessings
其他回答
use
import console
(width, height) = console.getTerminalSize()
print "Your terminal's width is: %d" % width
编辑:哦,对不起。这不是python标准库,这里是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])
我四处寻找,找到了窗户的解决方案:
http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/
这里有一个Linux的解决方案。
下面是一个在linux、os x和windows/cygwin上都可以运行的版本:
""" getTerminalSize()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
"""
__all__=['getTerminalSize']
def getTerminalSize():
import platform
current_os = platform.system()
tuple_xy=None
if current_os == 'Windows':
tuple_xy = _getTerminalSize_windows()
if tuple_xy is None:
tuple_xy = _getTerminalSize_tput()
# needed for window's python in cygwin's xterm!
if current_os == 'Linux' or current_os == 'Darwin' or current_os.startswith('CYGWIN'):
tuple_xy = _getTerminalSize_linux()
if tuple_xy is None:
print "default"
tuple_xy = (80, 25) # default value
return tuple_xy
def _getTerminalSize_windows():
res=None
try:
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
except:
return None
if res:
import struct
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
return sizex, sizey
else:
return None
def _getTerminalSize_tput():
# get terminal width
# src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
try:
import subprocess
proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
output=proc.communicate(input=None)
cols=int(output[0])
proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
output=proc.communicate(input=None)
rows=int(output[0])
return (cols,rows)
except:
return None
def _getTerminalSize_linux():
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:
return None
return int(cr[1]), int(cr[0])
if __name__ == "__main__":
sizex,sizey=getTerminalSize()
print 'width =',sizex,'height =',sizey
如果您使用的是Python 3.3或更高版本,我建议使用内置的get_terminal_size()。但是,如果您使用的是旧版本,想要一种简单的、跨平台的方式,那么可以使用asciimatics。这个包支持2.7以下的Python版本,并使用与上面建议的选项类似的选项来获取当前终端/控制台大小。
简单地构造Screen类并使用dimensions属性获取高度和宽度。这已经在Linux、OSX和Windows上被证明是有效的。
哦,在这里完全披露:我是作者,所以如果你在这方面有任何问题,请随时打开一个新的问题。
看起来代码有点问题,Johannes:
getTerminalSize需要导入操作系统 什么是env?看起来像os.environ。
另外,为什么要在返回之前切换线路和cols ?如果TIOCGWINSZ和stty都说行,那么cols,我说就这样吧。这让我困惑了10分钟,直到我注意到这种不一致。
Sridhar,我在管道输出时没有得到这个错误。我很确定它在尝试中被正确地捕获了——除了。
帕斯卡,“HHHH”在我的机器上不起作用,但“hh”可以。我很难找到这个函数的文档。它看起来依赖于平台。
chochem,合并。
以下是我的看法:
def getTerminalSize():
"""
returns (lines:int, cols:int)
"""
import os, struct
def ioctl_GWINSZ(fd):
import fcntl, termios
return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
# try stdin, stdout, stderr
for fd in (0, 1, 2):
try:
return ioctl_GWINSZ(fd)
except:
pass
# try os.ctermid()
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
return ioctl_GWINSZ(fd)
finally:
os.close(fd)
except:
pass
# try `stty size`
try:
return tuple(int(x) for x in os.popen("stty size", "r").read().split())
except:
pass
# try environment variables
try:
return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
except:
pass
# i give up. return default.
return (25, 80)
我正在尝试从这里调用stty大小的解决方案:
columns = int(subprocess.check_output(['stty', 'size']).split()[1])
然而,这对我来说失败了,因为我正在编写一个脚本,期望在stdin上重定向输入,stty会抱怨“stdin不是终端”。
我能做到这样:
with open('/dev/tty') as tty:
height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()