在python中是否有一种方法以编程方式确定控制台的宽度?我指的是一行中不换行的字符数,而不是窗口的像素宽度。

Edit

寻找在Linux上工作的解决方案


当前回答

我正在尝试从这里调用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()

其他回答

上面的代码在我的linux上没有返回正确的结果,因为winsize-struct有4个unsigned shorts,而不是2个signed shorts:

def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

HP和HP应该包含像素的宽度和高度,但不是。

@reannual的回答很好,但有一个问题:os。Popen现在已弃用。应该使用subprocess模块,所以这里有一个版本的@reannual的代码,它使用subprocess并直接回答了这个问题(通过直接将列宽度作为int值给出:

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

在OS X 10.9上测试

试着“祝福”

我也在找同样的东西。它非常易于使用,并提供了在终端中着色、造型和定位的工具。你需要的很简单:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

在Linux中工作就像一个魅力。(我不确定MacOSX和Windows)

在此下载及文件

或者你可以用pip安装它:

pip install blessings

我正在尝试从这里调用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()

从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