简体   繁体   中英

sys.stdout.write not working as expected in Python

I have two functions prints() and clear() . The function prints() print lines of text and the function clear() delete the printed lines with this method:

def clear():
    i = 0
    while True:
        if(i > globals['l']):
            break
        else:
            sys.stdout.write("\033[F \033[K")
            i += 1

where globals['l'] is the number of lines to clear.

Then after the function clear() runs and the lines are cleared, the function prints() run again etc...

I don't understand why the function clear() is clearing only 22 lines of 32 lines. But if I have, for example, 19 lines it is working perfectly. Where is the problem? How can I fix this?

Try this:

def clear(line_count):
    sys.stdout.write("\033[F \033[K" * line_count)
    sys.stdout.flush()

EDIT: Works only on Unix systems

You can use:

print("\033c")

Or:

import subprocess
subprocess.call(["printf", "\033c"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM