chetan honnavile
chetan honnavile

Reputation: 439

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?

Upvotes: 2

Views: 1240

Answers (3)

James Sapam
James Sapam

Reputation: 16940

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.

Upvotes: 3

salomonderossi
salomonderossi

Reputation: 2188

You can skip buffering for a whole python process by using python -u

Or when you need to use python 2, you could also replace sys.stdout with some other stream like wrapper which does a flush after every call.

class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import time
import sys
sys.stdout = Unbuffered(sys.stdout)
print '*',
time.sleep(2)
print '*'

Upvotes: 2

Byte Commander
Byte Commander

Reputation: 6736

The print statement of Python 2 is not as flexible as the function from Python 3.

If you used Python 3, you could simply specify the end character and whether to immediately flush the buffer like this:

print("*", end="", flush=True)

However, as you're using Python 2, you can not use the print statement but have to access the output stream object directly:

import sys
def progress_print(character="*"):
     sys.stdout.write(character)
     sys.stdout.flush()

This will force Python to not cache the printing data until one line is completed, but display it immediately by flushing the buffer.

Upvotes: 2

Related Questions