如何在控制台上的同一位置写入输出?

2024-05-08 15:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在编写一些脚本来自动从FTP服务器下载文件等。我想显示下载的进度,但我希望它保持在相同的位置,例如:

输出:

Downloading File FooFile.txt [47%]

我尽量避免这样的事情:

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

我该怎么做呢?


重复How can I print over the current line in a command line application?


Tags: 文件服务器txt脚本lineftp事情can
3条回答

使用终端处理库,如curses module

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

Python2

我喜欢以下几点:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

演示:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

演示:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

您还可以使用回车:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()

相关问题 更多 >