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
    see this https://stackoverflow.com/questions/493386/how-to-print-in-python-without-newline-or-space – zzn Aug 07 '16 at 02:39
  • 1
    also if you don't want to use sys see this [link](http://stackoverflow.com/questions/5598181/python-print-on-same-line) – Sen Qiao Aug 07 '16 at 02:42

2 Answers2

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
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!")
Blckknght
  • 100,903
  • 11
  • 120
  • 169