1

I am trying to use \r to print to the same line in bash (Ubuntu 16.04 terminal) but it doesn't work, as the program still prints frame number in a new line.

Here is the code

i = 0
while img is not None:
    print "Frame Number: {0}  \r".format(i)
    result = unwarp(img, xmap, ymap)
    result.save(disp)
    # Save to file
    fname = "../temp_data/frames/FY{num:06d}.png".format(num=i)
    result.save(fname)        
    img = vc.getImage()
    i = i + 1

I even tried using \x08 like this

print "Frame Number: {0}  \xO8".format(i)

but its still not working.

here is a sample output:

Frame Number: 0  
Frame Number: 1  
Frame Number: 2  
Frame Number: 3  
Frame Number: 4  
Frame Number: 5  
Frame Number: 6  
Frame Number: 7  
Frame Number: 8
TankorSmash
  • 12,186
  • 6
  • 68
  • 106
Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98

1 Answers1

1

Try it like this:

print "\rFrame Number: {:06d}".format(i),

Note the trailing , character on the print statement.

wim
  • 338,267
  • 99
  • 616
  • 750
  • wow this worked. can you please explain how it works? – Sapnesh Naik Mar 24 '17 at 19:21
  • That's just the Python 2 syntax for not appending a new-line automatically on a print statement. Weird, I know... it was fixed in Python 3. – wim Mar 24 '17 at 19:23
  • Thanks so much. and I notice that the line doesn't refresh spontaneously. is this bash related? – Sapnesh Naik Mar 24 '17 at 19:25
  • 1
    That's about output buffering - often stdout is line buffered. If you add a call to `sys.stdout.flush()` after the print statement, you should see every line – wim Mar 24 '17 at 19:41