How to rewrite output in terminal

后端 未结 4 1004
孤城傲影
孤城傲影 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条回答
  • 2020-12-25 13:46

    Using the blessings package - clear your screen (clear/cls) and enter:

    import sys
    from blessings import Terminal
    from time import sleep # <- boy, does this sound tempting a.t.m.
    
    term = Terminal()
    for i in range(6):
        with term.location(term.width - 3, term.height - 3):        
            print('{}'.format(i))
        sleep(2)
        if (i == 3):
            print('what was I doing, again?')
    print('done')
    

    To install it from CheeseShop, just...

    pip install blessings
    
    0 讨论(0)
  • 2020-12-25 13:56

    Based on this answer, but without the terminal controller:

    import time
    import sys
    for i in range(100):
        sys.stdout.write("Downloading ... %s%%\r" % (i))
        sys.stdout.flush()
        time.sleep(1)
    

    Tested on GNOME terminal (Linux) and Windows console.

    Tip: Don't run this example in IDLE editor.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-25 14:13

    Printing a carriage return (\r) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed:

    import time
    import sys
    for i in range(100):
        print i,
        sys.stdout.flush()
        time.sleep(1)
        print "\r",
    

    This doesn't clear the line, so if you try to, say, print decreasing numbers using this methods, you'll see leftover text from previous prints. You can work around this by padding out your output with spaces, or using some of the control codes in the other answers.

    0 讨论(0)
提交回复
热议问题