How do I write output in same place on the console

2019-01-02 22:06发布

I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:

output:

Downloading File FooFile.txt [47%]

I'm trying to avoid something like this:

     Downloading File FooFile.txt [47%]
     Downloading File FooFile.txt [48%]
     Downloading File FooFile.txt [49%]

How should I go about doing this?


Duplicate: How can I print over the current line in a command line application?

8条回答
手持菜刀,她持情操
2楼-- · 2019-01-02 22:53

A neat solution that has been working for me is:

from __future__ import print_function
import sys
for i in range(10**6):
    perc = float(i) / 10**6 * 100
    print(">>> Download is {}% complete      ".format(perc), end='\r')
    sys.stdout.flush()
print("")

The sys.stdout.flush is important otherwise it gets really clunky and the print("") on for loop exit is also important.

UPDATE: As mentioned in the comments, print also has a flush argument. So the following will also work:

from __future__ import print_function
for i in range(10**6):
    perc = float(i) / 10**6 * 100
    print(">>> Download is {}% complete      ".format(perc), end='\r', flush=True)
print("")
查看更多
爷的心禁止访问
3楼-- · 2019-01-02 22:57

You can also use the carriage return:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()
查看更多
登录 后发表回答