在 Python 中锁定终端窗口尺寸需要与操作系统交互,因为终端窗口的控制依赖于特定的系统 API。以下是一个跨平台的解决方案,分别针对 Windows、Linux 和 macOS 系统。
1.首先检测操作系统类型(Windows、Linux 或 macOS)
2.对于 Windows 系统,使用ctypes调用 Windows API 来设置控制台缓冲区大小和窗口大小
3.对于 Linux 和 macOS 系统,使用tput命令和ioctl系统调用来设置终端尺寸
4.提供了简单的错误处理机制
Windows 系统上,可以比较可靠地锁定终端窗口尺寸,在 Linux 和 macOS 系统上,由于终端类型多样,可能无法完全阻止用户调整窗口大小,但会尝试设置初始尺寸
import os
import sys
def lock_terminal_size(width, height):
"""
锁定终端窗口尺寸
参数:
width: 终端宽度(字符数)
height: 终端高度(字符数)
"""
if sys.platform.startswith('win32'):
# Windows系统
try:
import ctypes
from ctypes import wintypes
# 获取控制台句柄
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
hConsole = kernel32.GetStdHandle(-12) # STD_OUTPUT_HANDLE
# 设置缓冲区大小
buffer_info = wintypes.CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(hConsole, ctypes.byref(buffer_info))
# 设置窗口大小
success = kernel32.SetConsoleWindowInfo(
hConsole,
True,
ctypes.byref(wintypes.SMALL_RECT(0, 0, width - 1, height - 1))
)
# 设置缓冲区大小(防止窗口被拉伸)
success = kernel32.SetConsoleScreenBufferSize(
hConsole,
wintypes.COORD(width, height)
)
if not success:
raise ctypes.WinError(ctypes.get_last_error())
print(f"Windows终端尺寸已锁定为: {width}x{height}")
return True
except Exception as e:
print(f"Windows终端尺寸锁定失败: {e}")
return False
elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
# Linux或macOS系统
try:
# 首先尝试使用tput设置终端大小
os.system(f"tput cols {width}")
os.system(f"tput lines {height}")
# 对于支持的终端,使用ioctl进一步锁定
if sys.platform.startswith('linux'):
import fcntl
import termios
# 创建终端大小结构
size = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
# 设置新尺寸
fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ,
f"{width}\x00{height}\x00{size[2]}\x00{size[3]}\x00")
print(f"Unix终端尺寸已设置为: {width}x{height}")
print("注意:在某些Unix终端中,可能无法完全锁定尺寸,用户仍可手动调整")
return True
except Exception as e:
print(f"Unix终端尺寸设置失败: {e}")
return False
else:
print(f"不支持的操作系统: {sys.platform}")
return False
if __name__ == "__main__":
# 示例:锁定终端为80x24的大小
lock_terminal_size(80, 24)
# 保持程序运行,以便观察效果
try:
input("\n按Enter键退出...\n")
except KeyboardInterrupt:
pass