How to output the progress without line wrapping and refresh the display in the same location in Python?

import sys
num_batches = 20
for step in range(1,20):
    sys.stdout.write("processing: {} batch / {} batches.".format(step + 1, num_batches)+ " \r")
    sys.stdout.flush()

but the output is as follows:\ r doesn"t seem to work? Why is that?

Mar.25,2021

use a special control transfer sequence.

\ x1B [1A indicates that the cursor moves up one line, and \ x1B [K represents erasing the contents of the current cursor to the end of the line, which is equivalent to clearing the contents of the previous line.

sys.stdout.write('\x1B[1A\x1B[Kprocessing: {} batch / {} batches.'.format(step + 1, num_batches)+ ' \r')
Menu