在python中是否有一种方法以编程方式确定控制台的宽度?我指的是一行中不换行的字符数,而不是窗口的像素宽度。
Edit
寻找在Linux上工作的解决方案
在python中是否有一种方法以编程方式确定控制台的宽度?我指的是一行中不换行的字符数,而不是窗口的像素宽度。
Edit
寻找在Linux上工作的解决方案
当前回答
不确定为什么它在模块shutil中,但它在Python 3.3中出现在那里。看到的:
查询输出终端的大小
>>> import shutil
>>> shutil.get_terminal_size((80, 20)) # pass fallback
os.terminal_size(columns=87, lines=23) # returns a named-tuple
底层实现在os模块中。跨平台工作在Linux, Mac OS和Windows,可能是其他unix类。还有一个后端口,虽然已经无关紧要了。
其他回答
从Python 3.3开始,它是直接的: https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal
>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80
试着“祝福”
我也在找同样的东西。它非常易于使用,并提供了在终端中着色、造型和定位的工具。你需要的很简单:
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])
下面是一个应该与Linux和Solaris兼容的版本。根据来自madchine的帖子和评论。需要子流程模块。
def termsize(): import shlex, subprocess, re output = subprocess.check_output(shlex.split('/bin/stty -a')) m = re.search('rows\D+(?P\d+); columns\D+(?P\d+);', output) if m: return m.group('rows'), m.group('columns') raise OSError('Bad response: %s' % (output))
>>> termsize() ('40', '100')
import os
rows, columns = os.popen('stty size', 'r').read().split()
使用“stty size”命令,根据python邮件列表中的线程,该命令在linux上相当通用。它打开“stty size”命令作为文件,从中“读取”,并使用一个简单的字符串分割来分隔坐标。
不像操作系统。environ["COLUMNS"]值(尽管使用bash作为我的标准shell,但我不能访问),数据也将是最新的,而我相信os。environ["COLUMNS"]值只在python解释器启动时有效(假设用户自那时起调整了窗口的大小)。
(参见@GringoSuave关于如何在python 3.3+上做到这一点的回答)