题
Debian是容易的工具的输出结果在宽度均匀列。例如,尝试运行"aptitude搜索svn"..和所有的名字出现在首次列的相同的宽度。
现在,如果你调整终端,列宽度进行相应的调整。
是否有一个蟒蛇图书馆,使一个做到这一点?注意,图书馆必须知道终端的宽度,并采取一表作为输入-这可能是,例如, [('rapidsvn', 'A GUI client for subversion'), ...]
..你还可以规定一个最大宽度为第一栏(或任何列)。还注意如何在第二栏下修剪,如果超过终端宽..因此没有引入不希望第二线。
$ aptitude search svn
[...]
p python-svn-dbg - A(nother) Python interface to Subversion (d
v python2.5-svn -
v python2.6-svn -
p rapidsvn - A GUI client for subversion
p statsvn - SVN repository statistics
p svn-arch-mirror - one-way mirroring from Subversion to Arch r
p svn-autoreleasedeb - Automatically release/upload debian package
p svn-buildpackage - helper programs to maintain Debian packages
p svn-load - An enhanced import facility for Subversion
p svn-workbench - A Workbench for Subversion
p svnmailer - extensible Subversion commit notification t
p websvn - interface for subversion repositories writt
$
编辑:(在响应亚历克斯的回答以下)...输出将可以类似于'aptitude搜索'在于1)只有最后一栏(这是唯一一列有最长串在一个行)应修整,2)通常有2-4列,但最后一栏("说明")预计需要至少一半的终端宽度。3)的所有行含有同等数量的列,4)的所有项目都只字符串
解决方案
我不认为有一个大的跨平台的方式"得到宽度的终端"-- 大多数绝对不是 "看看所列环境变量"(见我的评论的问题)。在Linux和Mac OS X(我希望所有现代化的Unix versions),
curses.wrapper(lambda _: curses.tigetnum('cols'))
返回的数量列;但我不知道 wcurses 支持这个在窗。
一旦你做了(从操作系统。environ['列']如果你坚持的话,或通过课程,或从一个oracle的,或者违约80,或任何其他你喜欢的方式)的期望输出的宽度,其余的是 相当可行的。这是finnicky工作,与许多机会用于关闭一类型的错误,并且非常容易受到很多的的详细规格,你不完全清楚,例如:这柱被削减,以避免包裹--它始终是最后一个,或...?你怎么在表3中列样本输出当根据你的问题只有两个传递在...?什么是应该发生,如果不是所有的行具有相同的数列?必须的所有条目中表以串?和其他许多神秘的本之流。
因此,把有些任意猜测的所有规格,你不快,一种办法可能会喜欢的东西...:
import sys
def colprint(totwidth, table):
numcols = max(len(row) for row in table)
# ensure all rows have >= numcols columns, maybe empty
padded = [row+numcols*('',) for row in table]
# compute col widths, including separating space (except for last one)
widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)]
widths[-1] -= 1
# drop or truncate columns from the right in order to fit
while sum(widths) > totwidth:
mustlose = sum(widths) - totwidth
if widths[-1] <= mustlose:
del widths[-1]
else:
widths[-1] -= mustlose
break
# and finally, the output phase!
for row in padded:
for w, i in zip(widths, row):
sys.stdout.write('%*s' % (-w, i[:w]))
sys.stdout.write('\n')
其他提示
更新: : 这 colprint
例程现在可以在 应用 Python图书馆 在Github托管.
这是一个完整的程序,适合您感兴趣的人:
# This function was written by Alex Martelli
# http://stackoverflow.com/questions/1396820/
def colprint(table, totwidth=None):
"""Print the table in terminal taking care of wrapping/alignment
- `table`: A table of strings. Elements must not be `None`
- `totwidth`: If None, console width is used
"""
if not table: return
if totwidth is None:
totwidth = find_console_width()
totwidth -= 1 # for not printing an extra empty line on windows
numcols = max(len(row) for row in table)
# ensure all rows have >= numcols columns, maybe empty
padded = [row+numcols*('',) for row in table]
# compute col widths, including separating space (except for last one)
widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)]
widths[-1] -= 1
# drop or truncate columns from the right in order to fit
while sum(widths) > totwidth:
mustlose = sum(widths) - totwidth
if widths[-1] <= mustlose:
del widths[-1]
else:
widths[-1] -= mustlose
break
# and finally, the output phase!
for row in padded:
print(''.join([u'%*s' % (-w, i[:w])
for w, i in zip(widths, row)]))
def find_console_width():
if sys.platform.startswith('win'):
return _find_windows_console_width()
else:
return _find_unix_console_width()
def _find_unix_console_width():
"""Return the width of the Unix terminal
If `stdout` is not a real terminal, return the default value (80)
"""
import termios, fcntl, struct, sys
# fcntl.ioctl will fail if stdout is not a tty
if not sys.stdout.isatty():
return 80
s = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s)
height, width = struct.unpack("HHHH", size)[:2]
return width
def _find_windows_console_width():
"""Return the width of the Windows console
If the width cannot be determined, return the default value (80)
"""
# http://code.activestate.com/recipes/440694/
from ctypes import windll, create_string_buffer
STDIN, STDOUT, STDERR = -10, -11, -12
h = windll.kernel32.GetStdHandle(STDERR)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
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
else:
sizex, sizey = 80, 25
return sizex
好吧,才能使用 cwidget
要格式化仅文本显示中的列。你可以打电话 cwidget
为此编写Python扩展名,但我认为这是不值得的...您可以使用首选的方法来获取以char的实际水平尺寸并计算自己。
首先,使用 ioctl
要获得TTY的大小:
import termios, fcntl, struct, sys
def get_tty_size():
s = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s)
return struct.unpack("HHHH", size)[:2]
print get_tty_size()
然后使用这样的函数来制作列:
pad = lambda s, n=20: "%s%s" % (s,' '*(n-len(s)))
将它们放在一起,您将获得控制台的调整列!