Incomprehensible output of the python program in the Windows Terminal

Question:

I wrote a very ordinary python program. Print numbers from 0 to 50. But the work of the program in the Windows Terminal was absolutely incomprehensible to me.

Although in the settings there is "Command Prompt" as the default terminal application, at startup .py from the file manager (double-click on it), the program opens in Windows Terminal, but not in "Command Prompt", I don’t understand what to do with it.

When running the program through the executable file .py I have encountered this behavior:

Only the numbers from 21 to 29 that were placed in the terminal window and 21 empty lines before them were displayed on the terminal screen.

And when changing the size of the terminal window, even more incomprehensible things happened to me.

But when I run the file directly from the terminal, then everything is fine.

Operating system – Windows 11. File .py run in the default Windows Terminal. Python code:

for i in range(50):
    print(i)

Result of code execution:

first half of terminal

second half of terminal

Terminal when resizing:

terminal with modified sizes

Please help me understand the operation and device of the Windows Terminal when opening .py file. And how it can be fixed, what to do about it. I am grateful in advance.

Default terminal – “Command Prompt”:

command prompt

But it’s not this program that starts, but just Windows Terminal.

But if I put input() at the beginning of the program, then everything works fine:

input()
for i in range(50):
    print(i)

normal execution

Is it possible to solve this somehow without input()?

On the left is a not working program running through an executable file, on the right is a program running through a Command Line:

path

programs

Asked By: Mars Baboon

||

Answers:

The problem is that when text is output to the console on Windows, the ESC and CSI (Control Sequence Introducer) characters are not interpreted correctly, which can lead to unpredictable results.

One possible solution to the problem is to use the following Python code at the beginning of the file:

import os

os.system('cls')
os.system('color 07')
os.system('cls')

This code allows you to clear the console screen and reset the color scheme, which prevents unpredictable behavior when displaying text.

I found this solution using ChatGPT, a large language model developed by OpenAI. Unfortunately, the StackOverflow community couldn’t help me in any way. AI is superior in everything. I hope this will help you solve the problem! If you have any additional questions, feel free to ask them in the comments.

Do not forget to specify the source from which you received this solution (ChatGPT). I wish you good luck in your work!

Answered By: Mars Baboon