0

My code is print("Current progress : something", end = "\r") and keep repeating

Normally if the terminal is enough wider than the length of words to print, it looks normal as below : Normal

But if the length of words are longer than the width of terminal, it will start to making a new line and instead of carriage return to the line before, it will start at the new line Abnormal

My idea is not to print the excess code if the width is too small

And also set the specific width and height to the terminal of the user, I had used pywin32 to set this, but pywin32 not available to Linux user, so which module can I use in Linux with the same function with pywin32

Edit : I had made a code as below, but it still can't solve my problem

Length = shutil.get_terminal_size()[0]
print (" "*(Length-10), end = "\r") # Clear Last Line
ProgressPrint = f"Current Progress : {somephrase}\t{somephrase}\t{somephrase}"
print ( ProgressPrint[0:Length-10], end = "\r")
LynBean
  • 33
  • 5
  • try this, *https://stackoverflow.com/questions/566746/how-to-get-linux-console-window-width-in-python* – Popeye May 12 '22 at 06:59

1 Answers1

0

(This only answers the first part of question)

Why not try the f-string format specifier?

f"{some_name:10.10}"
# This truncate & limit some_name's length to 10

max_len = 10
f"{some_name:{max_len}.{max_len}}"  # same but with name instead of literal.

Demo:

import shutil
import time

width = shutil.get_terminal_size()[0]
print(f"Detected console width: {width}")


def limit_output(stuff_to_print, prefix="", suffix=""):

    free_length = width - len(prefix) - len(suffix)
    print(f"{prefix}{stuff_to_print:{free_length}.{free_length}}{suffix}", end="\r")


for n in range(10):
    time.sleep(0.5)
    limit_output("Meow Moo Bark" * (10 - n), f"Iteration {n} / ", "/ Nice suffix")

print()                                                                                                                                                                                                                                                                                                                                                                                                   

Output:

Detected console width: 128
Iteration 2 / Meow Moo Bark Meow Moo Bark Meow Moo Bark Meow Moo Bark Meow Moo Bark Meow Moo Bark Meow Moo Bark Meo/ Nice suffix
jupiterbjy
  • 2,882
  • 1
  • 10
  • 28
  • Can you please solve my 2nd question too :) I can't find the solution for changing the terminal width and height in Linux – LynBean May 12 '22 at 11:58
  • @Shinonon I'll try tinkering with it but might fail to find an answer. What you want is controlling size of the terminal? I never heard of stuff that can do that so far on linux.. Feel free to not accept my answer as I just wanted you to solve half the problem at least! – jupiterbjy May 12 '22 at 16:18