输出到同一行覆盖以前的输出? [英] Output to the same line overwriting previous output?
问题描述
我正在编写一个 FTP 下载器.部分代码是这样的:
I am writing an FTP downloader. Part of to the code is something like this:
ftp.retrbinary("RETR " + file_name, process)
我正在调用函数进程来处理回调:
I am calling function process to handle the callback:
def process(data):
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
file.write(data)
和输出是这样的:
1784 KB / KB 1829 downloaded!
1788 KB / KB 1829 downloaded!
etc...
但我希望它打印这一行,下次重新打印/刷新它,这样它只会显示一次,我会看到下载的进度.
but I want it to print this line and next time reprint/refresh it so it will only show it once and I will see progress of that download.
怎么做?
推荐答案
这是 Python 3.x 的代码:
Here's code for Python 3.x:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
end=
关键字在这里起作用——默认情况下,print()
以换行符结尾 (\n
)字符,但这可以用不同的字符串替换.在这种情况下,用回车结束行而不是将光标返回到当前行的开头.因此,对于这种简单的用法,无需导入 sys
模块.print()
实际上有 许多关键字参数 可用于大大简化代码.
The end=
keyword is what does the work here -- by default, print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys
module for this sort of simple usage. print()
actually has a number of keyword arguments which can be used to greatly simplify code.
要在 Python 2.6+ 上使用相同的代码,请将以下行放在文件顶部:
To use the same code on Python 2.6+, put the following line at the top of the file:
from __future__ import print_function
这篇关于输出到同一行覆盖以前的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!