python限制输出宽度_在python中,如何获取控制台窗口宽度_python_酷徒编程知识库...

我搜索了一下,找到了Windows的解决方案:

这里是Linux的解决方案。

下面是一个适用于Linux,OS X和Windows/CYGWIN的版本:""" getTerminalSize()

- get width and height of console

- works on linux,os x,windows,cygwin(windows)

"""

__all__=['getTerminalSize']

def getTerminalSize():

import platform

current_os = platform.system()

tuple_xy=None

if current_os == 'Windows':

tuple_xy = _getTerminalSize_windows()

if tuple_xy is None:

tuple_xy = _getTerminalSize_tput()

# needed for window's python in cygwin's xterm!

if current_os == 'Linux' or current_os == 'Darwin' or current_os.startswith('CYGWIN'):

tuple_xy = _getTerminalSize_linux()

if tuple_xy is None:

print"default"

tuple_xy = (80, 25) # default value

return tuple_xy

def _getTerminalSize_windows():

res=None

try:

from ctypes import windll, create_string_buffer

# stdin handle is -10

# stdout handle is -11

# stderr handle is -12

h = windll.kernel32.GetStdHandle(-12)

csbi = create_string_buffer(22)

res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

except:

return None

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

return sizex, sizey

else:

return None

def _getTerminalSize_tput():

# get terminal width

# src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window

try:

import subprocess

proc=subprocess.Popen(["tput","cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)

output=proc.communicate(input=None)

cols=int(output[0])

proc=subprocess.Popen(["tput","lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)

output=proc.communicate(input=None)

rows=int(output[0])

return (cols,rows)

except:

return None

def _getTerminalSize_linux():

def ioctl_GWINSZ(fd):

try:

import fcntl, termios, struct, os

cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))

except:

return None

return cr

cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)

if not cr:

try:

fd = os.open(os.ctermid(), os.O_RDONLY)

cr = ioctl_GWINSZ(fd)

os.close(fd)

except:

pass

if not cr:

try:

cr = (env['LINES'], env['COLUMNS'])

except:

return None

return int(cr[1]), int(cr[0])

if __name__ =="__main__":

sizex,sizey=getTerminalSize()

print 'width =',sizex,'height =',sizey

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值