Reputation: 455
I am working on a little text based console game using Python. Because I am using some ASCII art I have to ensure that the width of the console is the same for everyone after launch of my game. Can anyone tell me how to set the console width and height ? :)
Greetz
Flo
Upvotes: 8
Views: 28436
Reputation: 36623
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)
Upvotes: 0
Reputation: 23
Kudo's to Malte Bublitz for already explaining why this works (Python 3+):
os.system(f'mode con: cols={cols} lines={lines}')
Upvotes: 1
Reputation: 161
a) To check the size of the Terminal Window
import os
x = os.get_terminal_size().lines
y = os.get_terminal_size().columns
print(x)
print(y)
b) To change the size of the Terminal Window
import os
cmd = 'mode 50,20'
os.system(cmd)
c) To change the color of the Terminal Window
import os
cmd = 'color 5E'
os.system(cmd)
Upvotes: 16
Reputation: 236
The easiest way is to execute the mode command.
e.g. for a 80x25 window:
C:\> mode con: cols=25 lines=80
Or in Python:
subprocess.Popen(["mode", "con:", "cols=25", "lines=80"])
Upvotes: 8