0

How can i show "dynamic" messages into loop? For example:

for item in array:
print (item + " > Cheking file", end=" ")
#Conditions which takes some time. Create a zip file or smth else..
   if (some condition):
      print ("> Creating archive", end=" ")
#Another conditions which takes some time.
   if (some condition):
      print ("> Done!")

I thought that the result must be:

FILENAME > Checking file ... *tick tock* ... > Creating archive ... *tick tock* ... > Done!

But the line appeares entirely after each loop cycle. How can show messages like CMD style?

2

2 Answers 2

1

The issue you have with the messages not showing up until after the last print is probably due to buffering. Python's standard output stream is line-buffered by default, so you won't see the text you've printed until a newline is included in one of them (e.g. when no end parameter is set).

You can work around that buffering by passing flush=True in the calls where you're setting end. That will tell Python to flush the buffer even though there has not been a newline written.

So try:

for item in array:
    print(item + " > Cheking file", end=" ", flush=True)
    #Conditions which takes some time. Create a zip file or smth else..
    if some_condition:
        print("> Creating archive", end=" ", flush=True)
    #Another conditions which takes some time.
    if some_other_condition:
        print("> Done!")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
1

This is due to buffering of the output stream. You can flush the stream after each write with the flush option to print():

for item in 'a', 'b', 'c':
    print (item + " > Cheking file", end=" ", flush=True)
   if (some condition):
      print ("> Creating archive", end=" ", flush=True)
   if (some condition):
      print ("> Done!")

It's not necessary for the last print (although it won't hurt) since that will print a new line which will flush the output.

Note also that you will want to print a new line at the end of each iteration. Considering that you are printing conditionally, the final print might not actually occur, so it's a good idea to use end=' ' in all of the prints, and then print a new line at the end of each iteration:

for item in 'a', 'b', 'c':
    print (item + " > Cheking file", end=" ", flush=True)
   if (some condition):
      print ("> Creating archive", end=" ", flush=True)
   if (some condition):
      print ("> Done!", end=' ')
   print()

Now, if for some reason the final condition is not True, a new line will still be printed.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.