Set Console Width (Windows, Python)
Asked Answered
C

3

8

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

Contiguous answered 1/11, 2012 at 10:29 Comment(1)
This may help you: How can I change the width of a Windows console window?Sol
L
8

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"])
Libido answered 1/11, 2012 at 10:43 Comment(4)
Ok I imported subprocess but it still does not work :c i get a "FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden" error -.-Contiguous
Ok got it working by myself ;) I just used os.system("mode con: cols=25 lines=80")Contiguous
LOL, mode is a cmd command, not a executable, subprocess.Popen(["mode", "con:", "cols=25", "lines=80"]) definitely does not work.Vanir
@Vanir There's nothing to "LOL" at. Everyone makes mistakes. You could instead request an edit to the comment...Corporation
S
16

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)
Sheepfold answered 28/10, 2018 at 11:18 Comment(3)
This answered my next question! A follow-up is that it is for 3.3 or higher, so Python 2 users need to import future.Crosley
How can I reset the size?Aircrew
This is super - but I guess as part of the functionality of the mode command the scroll bar disappears :-/Rearm
L
8

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"])
Libido answered 1/11, 2012 at 10:43 Comment(4)
Ok I imported subprocess but it still does not work :c i get a "FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden" error -.-Contiguous
Ok got it working by myself ;) I just used os.system("mode con: cols=25 lines=80")Contiguous
LOL, mode is a cmd command, not a executable, subprocess.Popen(["mode", "con:", "cols=25", "lines=80"]) definitely does not work.Vanir
@Vanir There's nothing to "LOL" at. Everyone makes mistakes. You could instead request an edit to the comment...Corporation
K
1

Kudo's to Malte Bublitz for already explaining why this works (Python 3+):

os.system(f'mode con: cols={cols} lines={lines}')
Klaus answered 7/4, 2022 at 15:13 Comment(1)
Not system independent though, Windows only, for MacOS see: #59357299Klaus

© 2022 - 2024 — McMap. All rights reserved.