Python 输出到同一行覆盖以前的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4897359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Output to the same line overwriting previous output?
提问by Kristian
I am writing an FTP downloader. Part of to the code is something like this:
我正在编写一个 FTP 下载器。部分代码是这样的:
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)
and output is something like this:
和输出是这样的:
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.
但我希望它打印这一行,下次重新打印/刷新它,这样它只会显示一次,我会看到下载的进度。
How can it be done?
怎么做到呢?
采纳答案by Kudzu
Here's code for Python 3.x:
这是 Python 3.x 的代码:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
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 sysmodule for this sort of simple usage. print()actually has a number of keyword argumentswhich can be used to greatly simplify code.
该end=关键字是什么做的工作在这里-在默认情况下,print()在一个换行符(结束\n)字符,但可以使用不同的字符串替换。在这种情况下,以回车结束行而不是将光标返回到当前行的开头。因此,没有必要sys为这种简单的用法导入模块。print()实际上有许多关键字参数可以用来大大简化代码。
To use the same code on Python 2.6+, put the following line at the top of the file:
要在 Python 2.6+ 上使用相同的代码,请将以下行放在文件顶部:
from __future__ import print_function
回答by Andrea Spadaccini
Have a look at the curses module documentationand the curses module HOWTO.
Really basic example:
非常基本的例子:
import time
import curses
stdscr = curses.initscr()
stdscr.addstr(0, 0, "Hello")
stdscr.refresh()
time.sleep(1)
stdscr.addstr(0, 0, "World! (with curses)")
stdscr.refresh()
回答by Sam Dolan
If all you want to do is change a single line, use \r. \rmeans carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, \bcan be used to go one character backward. (some terminals may not support all those features)
如果您只想更改一行,请使用\r. \r表示回车。它的作用仅仅是将插入符号放回当前行的开头。它不会擦除任何东西。同样,\b可用于向后移动一个字符。(某些终端可能不支持所有这些功能)
import sys
def process(data):
size_str = os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
sys.stdout.write('%s\r' % size_str)
sys.stdout.flush()
file.write(data)
回答by Bouke Versteegh
Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.
这是我的小班,可以重印文本块。它会正确清除以前的文本,因此您可以用较短的新文本覆盖旧文本,而不会造成混乱。
import re, sys
class Reprinter:
def __init__(self):
self.text = ''
def moveup(self, lines):
for _ in range(lines):
sys.stdout.write("\x1b[A")
def reprint(self, text):
# Clear previous text by overwritig non-spaces with spaces
self.moveup(self.text.count("\n"))
sys.stdout.write(re.sub(r"[^\s]", " ", self.text))
# Print new text
lines = min(self.text.count("\n"), text.count("\n"))
self.moveup(lines)
sys.stdout.write(text)
self.text = text
reprinter = Reprinter()
reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")
回答by Matt Ellen
I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.
我发现对于 python 2.7 中的简单打印语句,只需在'\r'.
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',
This is shorter than other non-python 3 solutions, but also more difficult to maintain.
这比其他非 python 3 解决方案更短,但也更难维护。
回答by Moustafa Saleh
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
您可以在字符串的末尾添加 '\r' 并在打印函数的末尾添加一个逗号。例如:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
回答by JoePythonKing
I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - https://github.com/spyder-ide/spyder/issues/3437
我正在使用 spyder 3.3.1 - windows 7 - python 3.6 尽管可能不需要刷新。基于这篇文章 - https://github.com/spyder-ide/spyder/issues/3437
#works in spyder ipython console - \r at start of string , end=""
import time
import sys
for i in range(20):
time.sleep(0.5)
print(f"\rnumber{i}",end="")
sys.stdout.flush()
回答by Amirouche Zeggagh
to overwiting the previous line in python all wath you need is to add end='\r'to the print function, test this example:
要覆盖 python 中的前一行,你需要的是将end='\r' 添加到打印函数中,测试这个例子:
import time
for j in range(1,5):
print('waiting : '+j, end='\r')
time.sleep(1)

