Search code examples
python-2.7console-output

Print command-line progress bar horizontally


#!/usr/bin/python
import time

count  = 5
temp = True
while temp:
        if count < 1:
                print "done",
                temp = False
        else:
                print "*"
                time.sleep(2)
                count -= 1

output:

*
*
*
*
*
done

Please note that here "*" in output is printed one after the other on the screen at the interval of 2 seconds(this is exactly what i wanted),i need to use this as a progress bar in some other code.

  1. I used print "*", however the output is horizontal but it prints all at once after the program execution.

    >>>* * * * * done
    
  2. using end keyword gives this error.

    File "progress_1_.py", line 11
     print ("*",end = '')
                        ^
    SyntaxError: invalid syntax
    

Python version is Python 2.7.5 .

I cannot upgrade Python on this prod machine and need to deal with the existing version to get the desired output.

So, considering the above cases, instead of printing in new line ,can it be printed horizontally one after the other at the interval of 2 secs?


Solution

  • Here is one simple answer:

    #!/usr/bin/python
    
    import sys
    import time
    
    def wait(n):
        time_counter = 0
        while True:
            time_counter += 1
            if time_counter <= n:
                time.sleep(1)
                sys.stdout.write("*")
                sys.stdout.flush()
            else:
                break
        sys.stdout.write("\n")
    wait(10)
    
    Output:
    
    **********
    

    You can modify the way you want.