Carriage Return not working in IDLE?
Asked Answered
C

2

10

I'm trying to create a code for a countdown timer that stays in place: so that each line overwrites the previous one. This is what I have so far:

import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = "{:02d}:{:02d}".format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print("That's the end! You lose...\n\n\n\n\n")
    exit()

countdown(10)

The output, however, is:

00:10
00:09
00:08
...
00:00
That's the end! You lose...

Why is the carriage return seemingly not working?

Claudy answered 3/3, 2016 at 9:32 Comment(7)
What OS are you on? How are you running the program? It works for me on Windows 7 through the Windows command prompt, so the problem could be OS specific.Intrinsic
It works on Ubuntu in a terminal too. The issue is most likely that your terminal (or whatever displays the output) does not understand CR -- your python code is fine (I would add flush=True, to be explicit, but it should work as is).Sallee
Same environment/results as @Intrinsic for me. Working well.Delitescence
I'm using Mac OS X Yosemite on the newest version of IDLE. Sorry for the long time before a reply, I've been busy over the past week.Claudy
Ok, this doesn't work in IDLE for me either. The proposed answer below doesn't either. So this has something to do with how IDLE handles certain characters. I believe idle is built with Tkinter which itself rests on Tcl/Tk, so I'm not sure how deeply the problem occurs. IDLE is probably not the best place to run programs like this. Instead run it using a proper shell.Intrinsic
I ran the code using a Python shell, and it worked well. You're right, Matthew, it must be something to do with IDLE handling these instructions. Thanks also to J.F. Sebastian for first pointing out the problem. Cheers all.Claudy
@Matthew: the tk Text widget does not interpret anything other than '\n'. You are correct the IDLE is not meant for production running of programs. It is a development and learning environment. For that purpose, it has been decided that displaying output 'as is' is better. The other issue is that different environments that interpret control characters do not all act the same.Sawhorse
S
8

IDLE doesn't support most control characters such as \r, \b. It is still true in 2020 (no support in Python 3.9)

\r should work if you start Python REPL in a Unix terminal or in Windows console instead.

Sallee answered 14/3, 2016 at 10:35 Comment(0)
D
2

When \r doesn't work, try \x08 (backspace), and add the flush=True to be safe:

print('\x08' * 5 + timeformat, end='', flush=True)
Denude answered 8/3, 2016 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.