我认为没有通用的跨平台方式来“获取终端的宽度”- 绝对不是 “查看COLUMNS环境变量”(请参阅我对问题的评论)。在Linux和Mac OS
X(我希望所有现代Unix版本)上,
curses.wrapper(lambda _: curses.tigetnum('cols'))返回列数;但我不知道wcurses是否在Windows中支持此功能。
一旦确定了输出宽度(如果您坚持要使用os.environ
[‘COLUMNS’],或者通过curses,或者是从oracle,或者默认为80,或者您希望的其他方式),那么其余的就很可行了。这是一项艰巨的工作,很可能会出现一种错误,并且很容易受到许多您无法完全弄清楚的详细规格的影响,例如:哪一列被剪掉以避免换行-
它总是最后一个,还是…?当根据您的问题仅传入两列时,您如何在示例输出中显示3列?如果不是所有行都具有相同的列数,应该怎么办?表中的所有条目都必须是字符串吗?以及许多其他类似的谜团。
因此,对您不表达的所有规格进行一些随意的猜测,一种方法可能类似于…:
import sysdef 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')


