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

Edit

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


当前回答

如果在调用此脚本时没有控制终端,那么这里的许多Python 2实现都将失败。您可以检查sys.stdout.isatty()来确定这是否实际上是一个终端,但这将排除一些情况,因此我认为最python化的方法来计算终端大小是使用内置的curses包。

import curses
w = curses.initscr()
height, width = w.getmaxyx()

其他回答

如果在调用此脚本时没有控制终端,那么这里的许多Python 2实现都将失败。您可以检查sys.stdout.isatty()来确定这是否实际上是一个终端,但这将排除一些情况,因此我认为最python化的方法来计算终端大小是使用内置的curses包。

import curses
w = curses.initscr()
height, width = w.getmaxyx()

上面的代码在我的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应该包含像素的宽度和高度,但不是。

下面是一个应该与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')

从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