0

Given an instance here.

For Linux, a down-counter can be implemented as:

# work for Linux
import time
for a in [999,55,1]:
    print(f'\033[K{a}',end='\r')
    time.sleep(1)

But it doesn't work for Windows. The key is that the current line cannot be cleared by print('\033[K'+'Anything', end='\r'), although it works for Linux.

I know another way using many space symbols:

for a in [999,55,1]:
    print(f'{a}  ',end='\r') # two space symbols
    time.sleep(1)

However it is not always perfect, if the list is changed:

for a in [8888888,77,3]:
    print(f'{a}  ',end='\r') # space symbols are not enough
    time.sleep(1)

And I don't like the followed space symbols.

How to clear the current line in the Windows console with Python? Avoid using packages for simplicity.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
Kani
  • 1,072
  • 2
  • 7
  • 16

2 Answers2

1

I found it in Python: How can I make the ANSI escape codes to work also in Windows?

This works well:

# work for Linux & Windows
import time
import platform

if platform.system() == 'Windows':
    from ctypes import windll
    windll.kernel32.SetConsoleMode(windll.kernel32.GetStdHandle(-11), 7)

for a in [999,55,1]:
    print(f'\033[K{a}',end='\r')
    time.sleep(1)
Kani
  • 1,072
  • 2
  • 7
  • 16
0

You can dynamically pad spaces depending on the list values in f-strings as f'{a:<{m}}':

import time

lst = [9999999,55,1]
m = max(len(str(x)) for x in lst)
for a in lst:
    print(f'{a:<{m}}', end='\r') # m space symbols
    time.sleep(1)
Austin
  • 25,759
  • 4
  • 25
  • 48
  • If an iterator is used instead of a list and its elements cannot be gotten immediately (eg. some output when training a big neural network model in each epoch), `m` cannot be gotten before `for`. Do you have a better idea? – Kani Aug 31 '20 at 06:18