Skip to content Skip to sidebar Skip to footer

How To Overwrite Multiline Print In Python?

There is some code that displays the function process: all_nums = 100 counter = 0 def status(num, counter): print( f'Current number {num}', f'Numbers done: {co

Solution 1:

Use some ANSI escape codes to control your terminal: (from https://stackoverflow.com/a/11474509/8733066) "\033[F" makes the terminal cursor go up one line, *3 is because there are 3 lines

def status(num, counter):
    print("\033[F"*3)
    print(
        f'Current number {num}',
        f'Numbers done: {counter}, all nums: {all_nums}',
        f'{(num/all_nums):2.1%}',
        sep="\n"
    )

# call this before the for loop:
print("\n"*3, end="")

Solution 2:

all_nums = 100
counter = 0

def status(num, counter):
    print(
        f'Current number {num}',
        f'Numbers done: {counter}, all nums: {all_nums}',
        f'{(num/all_nums):2.1%}',
        flush=False, end='\r'
    )
    print()


for x in range(all_nums):
    counter += 1
    status(x, counter)
    time.sleep(0.1)

Post a Comment for "How To Overwrite Multiline Print In Python?"