且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

输出到同一行覆盖以前的输出?

更新时间:2023-12-04 12:22:10

这是 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