##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <<TableOfContents>> ## 默许导航,请保留 <<Include(ZPyUGnav)>> = 获得命令行宽/高 = ##startInc == 问题 == {{{ Zengming Zhang <nicegiving@gmail.com> sender-time Sent at 01:30 (GMT+08:00). Current time there: 10:58 AM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Sun, Apr 18, 2010 at 01:30 }}} subject [CPyUG] 请问下如何在python中获得命令行终端的宽度? * 在写python命令行程序的时候,如果能获取当前命令行终端的长度,就可以根据这个值来格式化输出的内容,使得输出的内容更加整洁美观。 === 宽度 === 我找到解决方法了,请参见下面的程序: get_terminal_width.py` {{{ #!python import commands def get_terminal_width_resize(): c = commands.getoutput('resize').split('\n') c = [x for x in c if x.startswith('COLUMNS=')] if c: c = c[0] dummy, c = c.split('=', 1) if c[-1] == ';': c = c[:-1] if c: return int(c) else: return None print get_terminal_width_resize() }}} * 注意: 本程序拷贝自Radovan Garabík的pydf,用于更好的查看硬盘分区及使用状况。 在此附上Radovan Garabík的版权说明: {{{ zzm@zzm-desktop:~/Downloads/cli-tools/pydf/pydf-8$ more COPYING This package was written by Radovan Garabík <garabik @ kassiopeia.juls.savba.sk> Copyright: Public domain. Do whatever you want to do with this program. }}} === 高度 === 同样可以得到获得终端高度的程序: {{{ #!python import commands def get_terminal_height(): c = commands.getoutput('resize').split('\n') c = [x for x in c if x.startswith('LINES=')] if c: c = c[0] dummy, c = c.split('=', 1) if c[-1] == ';': c = c[:-1] if c: return int(c) else: return None print get_terminal_height() }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<<DateTime(2010-04-19T10:59:53+0800)>>]