以上方法是针对python3.3开始以及以后的版本,在3.3之前,我们只能通过第三方模块,或者windowsAPI来获得。
小编电脑上有安装Python2,在Python2中就相当麻烦了。
详细代码如下:
#-*- coding:utf-8 -*-
from ctypes import windll, create_string_buffer
win_stdout = -11
fd = windll.kernel32.GetStdHandle(win_stdout)
#获得标准输出的句柄
cstruct = create_string_buffer(22)
rc_struct = windll.kernel32.GetConsoleScreenBufferInfo(fd, cstruct)
#获得控制台的属性
if rc_struct:
import struct
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", cstruct)
sizex = right - left + 1
sizey = bottom - top + 1
#计算控制台宽高
#python2 编码处理,转换成gb2312
mystr = ("宽度 = %d,高度 = %d" %(sizex,sizey)).decode('utf-8').encode('gb2312')
print(mystr)