0

How can I clear/save the current line in Python? I have a double loop that I would like to print the results of the inner loop on-line and save and show the final result of this loop after it goes to the outer loop each time. I have:

import os
for j in xrange(1,final_step_j):
    Result=0
        for k in xrange(1,final_step_k):
         Result=Result+ j*k
         os.system('clear')
         print "current Result for j=%s and k=%s is %s" %(j, k, Result) 

Which os.system('clear') clearly clear the whole page every time it runs the inner loop. I want to save and show the final result of the inner loop each time and go to a new line for showing the result of the next round while the previous last line is still visible on the screen.

braX
  • 11,506
  • 5
  • 20
  • 33
Rotail
  • 1,025
  • 4
  • 19
  • 40

1 Answers1

1

It's not perfect, but you could try writing a carriage return \r without a new line via the lower level stdout method:

import os
import sys

for j in xrange(1,final_step_j):
  Result=0
  for k in xrange(1,final_step_k):
    Result=Result+ j*k
    # Move back to beginning and print over
    sys.stdout.write("\rcurrent Result for j=%s and k=%s is %s" %(j, k, Result)) 
    sys.stdout.flush() # Flush without a new line
  print # Move to next line

The problem is if the line you're printing is shorter than the one you've already printed in which case you need to have more padding or make sure you have a constant amount of padding.

Based on this answer.

Community
  • 1
  • 1
Ric
  • 8,615
  • 3
  • 17
  • 21