Search code examples
pythonpython-3.xwindowsprintingconsole

Append to previous line


I'm doing folder/file processing in Python. To notify the user, I output some messages to the console. These messages look similar to this:

Creating folders...
DONE
Creating files...
DONE
All done!

This is fine if the process is short, but in my case, the process (and the messages) is not short. I don't want to waste new lines on the success/fail messages. I want them to look like this:

Creating folders... DONE
Creating files... DONE
All done!

The trick is to have "DONE" strings append to previous line after the specific task is completed. So, first I just see:

Creating folders...

and when the task is done, it becomes:

Creating folders... DONE

and moves on to the next task. I've tried not ending the lines, but it didn't work:

print("Creating folders... ", end="")
time.sleep(2) # fake process
print("DONE")
time.sleep(1)
print("Creating files... ", end="")
time.sleep(2)
print("DONE")

Well, it works, but both strings (task... result) show up at the same time (after the task is done). I don't see the transition I've mentioned above.

I've found another way, move to the start of the line and replace the string:

print("Creating folders... ", end="\r")
time.sleep(2) # fake process
print("Creating folders... DONE")
time.sleep(1)
print("Creating files... ", end="\r")
time.sleep(2)
print("Creating files... DONE")

This seems to produce the desired effect, but I'm repeating and extending the previous message. I'd rather just output the result, not repeat the task message again.

Is there a simpler solution to this?


Also, why doesn't the first method I've tried work? I print a text, and not end the line. After some time I add another text and this gets appended to the previous line, because there's no line-break. Since there's time difference between two prints, I should see the transition, but I don't. They get printed at the same time. Why is that?


Solution

  • You need to flush the buffer after each print statement (that uses end="") in order to ensure that the messages are pushed to the console immediately. See print() documentation.

    Working Example with flush parameter of print function:

    import time
    
    print("Creating folders... ", end="", flush=True)
    time.sleep(2)  # fake process
    print("DONE")
    time.sleep(1)
    print("Creating folders... ", end="", flush=True)
    time.sleep(2)
    print("DONE")
    

    Working Example with manual flushing:

    import time
    import sys
    
    print("Creating folders... ", end="")
    sys.stdout.flush()
    time.sleep(2) # fake process
    print("DONE")
    time.sleep(1)
    print("Creating files... ", end="")
    sys.stdout.flush()
    time.sleep(2)
    print("DONE")
    

    See it in action!