0

I want to overwrite the output of my programme so that each line overwrites the previous one. I know that I can use carriage return for this. This is where things get interesting.

This is working fine:

for x in range(10):
    print(x, end='\r')
    time.sleep(0.1)

However, this, which is what I need to do, is not wrking:

def ft_progress(list):
    to_print = range(0, len(list), min(int(len(list) / 30) + 1, 30))
    for i2 in list:
        i = abs(i2)
        print("[", str("%.2f" % (100 * (i + 1) / len(list))).rjust(6), "% ]", end='\r')
        yield i


for elem in ft_progress(X):
    ret += (elem + 3) % 5
    time.sleep(0.01)
    print()
    print(ret)

I need the yield to return a value as well, that I will need to print. In this last case, the output is not overwritten. Why is this happening? It is driving me nuts. I have already tried things like starting the print statement with '\r', but it is not working.

kubo
  • 221
  • 1
  • 8
  • 1
    It's not happening because the loop that calls it is printing additional lines in between each iteration. – Barmar Apr 14 '23 at 17:19
  • If you just want to see the final result, take `print()` and `print(ret)` out of the loop. – Barmar Apr 14 '23 at 17:21
  • It'd help to make a [mre]. `X` and `ret` are not defined, and `to_print` is unused. Plus you could clean up the string formatting, like `print(f"[ {100 * (i + 1) / len(list):6.2f} % ]", end='\r')`. Lastly, `list` is a bad variable name since it [shadows](//en.wikipedia.org/wiki/Variable_shadowing) the [builtin `list` type](//docs.python.org/3/library/stdtypes.html#list). In example code it's not a big problem, but it is confusing, so it'd be better to use a more descriptive name, or at least something like `lst`. – wjandrea Apr 14 '23 at 17:22
  • Related, may be useful: [Progress Bar Among Other Print Statements Not Working](https://stackoverflow.com/q/55620924/4518341) – wjandrea Apr 14 '23 at 17:23
  • 1
    If you want a progress bar and also other output, you could use ncurses to create a full-screen application. – Barmar Apr 14 '23 at 17:25

0 Answers0