How to animate the command line?

前端 未结 8 1854
臣服心动
臣服心动 2020-11-27 09:09

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar

相关标签:
8条回答
  • 2020-11-27 10:05

    Here is the answer for your question... (python)

    def disp_status(timelapse, timeout):
      if timelapse and timeout:
         percent = 100 * (float(timelapse)/float(timeout))
         sys.stdout.write("progress : ["+"*"*int(percent)+" "*(100-int(percent-1))+"]"+str(percent)+" %")
         sys.stdout.flush()
         stdout.write("\r  \r")
    
    0 讨论(0)
  • 2020-11-27 10:09

    One way to do this is to repeatedly update the line of text with the current progress. For example:

    def status(percent):
        sys.stdout.write("%3d%%\r" % percent)
        sys.stdout.flush()
    

    Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints "\r\n" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).

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