How to rewrite output in terminal

后端 未结 4 1021
孤城傲影
孤城傲影 2020-12-25 13:22

I have a Python script and I want to make it display a increasing number from 0 to 100% in the terminal. I know how to print the numbers on the terminal but how can I \"rewr

4条回答
  •  Happy的楠姐
    2020-12-25 13:57

    This recipe here should prove useful. Using that module as tc, the following code does what you want:

    from tc import TerminalController
    from time import sleep
    import sys
    
    term = TerminalController()
    
    for i in range(10):
        sys.stdout.write("%3d" % i)
        sys.stdout.flush()
        sleep(2)
        sys.stdout.write(term.BOL + term.CLEAR_EOL)
    

    The recipe uses terminfo to get information about the terminal and works in Linux and OS X for a number of terminals. It does not work on Windows, though. (Thanks to piquadrat for testing, as per the comment below).

    Edit: The recipe also gives capabilities for using colours and rewriting part of the line. It also has a ready made text progress bar.

提交回复
热议问题