Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

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: {counter}, all nums: {all_nums}',
        f'{(num/all_nums):2.1%}',
        flush=False, end='
'
    )


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

It works. But I want to split this text on a line. When I add to any place everything breaks.

Current number 1, all nums: 100 0.0%
Current number 2, all nums: 100 1.0%
Current number 3, all nums: 100 2.0%
Current number 4, all nums: 100 3.0%

How can I overwrite console output in multiple lines?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...