If you are using Windows Terminal or Windows Command Prompt, this function resizes a window by setting the title of the terminal/prompt, finding that title, and then resizing using the Windows API.
Note: if another windows shares the same title, it might resize that window first.
import ctypes
import subprocess
import time
def resize_terminal(width: int, height: int, title: str='[Python]') -> None:
"""
Resizes the Windows Terminal or CMD prompt after setting the title.
args:
width: new window width in pixels
height: new window height in pixels
title: title of the window
returns:
None
"""
subprocess.run(['title', str(title)], shell=True)
# small delay to allow the title change to propagate
# if it cannot find it after 0.25 seconds, give up
for _ in range(10):
hwnd = ctypes.windll.user32.FindWindowW(None, title)
if hwnd:
break
time.sleep(0.025)
else:
print('Could not location window')
return
HWND_TOP = 0 # set the z-order of the terminal to the top
SWP_NOMOVE = 0x0002 # ignores the x and y coords. resize but don't move.
SWP_NOZORDER = 0x0004 # ignores the changing the zorder.
flags = SWP_NOMOVE + SWP_NOZORDER
ctypes.windll.user32.SetWindowPos(hwnd, HWND_TOP, 0, 0, width, height, flags)