打印到同一行而不是新行?[重复]
- 2025-04-16 08:58:00
- admin 原创
- 19
问题描述:
基本上我想做与这个家伙相反的事情......呵呵。
Python 脚本:每次向 shell 打印新行而不是更新现有行
我有一个程序可以告诉我进展如何。
for i in some_list:
#do a bunch of stuff.
print i/len(some_list)*100," percent complete"
所以如果 len(some_list) 是 50,我会把最后一行打印 50 次。我想打印一行并不断更新这一行。我知道这可能是你今天遇到的最无聊的问题了。我实在想不出要在谷歌里输入这四个字才能找到答案。
更新!我试了mvds的建议,感觉不错。新代码
print percent_complete,"
",
完成百分比只是一个字符串(我第一次抽象了它,现在我试图将其转化为字面量)。现在的结果是,它运行程序,直到程序结束才打印任何内容,然后在一行中打印“100% 完成”。
如果没有回车符(但有逗号,这是 mvds 建议的一半),它直到最后才打印任何内容。然后打印:
0 percent complete 2 percent complete 3 percent complete 4 percent complete
等等。现在的新问题是,逗号直到程序完成才会打印。
如果有回车符而没有逗号,其行为与没有逗号时的行为完全相同。
解决方案 1:
这叫做回车符,或者`
`
使用
print i/len(some_list)*100," percent complete
",
逗号可防止打印添加换行符。(并且空格将使该行与之前的输出保持清晰)
另外,不要忘记以 a 终止,print ""
以至少获得最终的换行符!
解决方案 2:
在 Python 3.3+ 中,您不需要sys.stdout.flush()
.print(string, end='', flush=True)
工作。
所以
print('foo', end='')
print('
bar', end='', flush=True)
将用“bar”覆盖“foo”。
解决方案 3:
对我来说,有效的方法是结合 Remi 和 siriusd 的答案:
from __future__ import print_function
import sys
print(str, end='
')
sys.stdout.flush()
解决方案 4:
从 python 3.x 开始你可以执行以下操作:
print('bla bla', end='')
(也可以通过将其放在from __future__ import print_function
脚本/模块的顶部在 Python 2.6 或 2.7 中使用)
Python 控制台进度条示例:
import time
# status generator
def range_with_status(total):
""" iterate from 0 to total and show progress in console """
n=0
while n<total:
done = '#'*(n+1)
todo = '-'*(total-n-1)
s = '<{0}>'.format(done+todo)
if not todo:
s+='
'
if n>0:
s = '
'+s
print(s, end='')
yield n
n+=1
# example for use of status generator
for i in range_with_status(10):
time.sleep(0.1)
解决方案 5:
入坑已晚——但由于这些答案对我都不起作用(我没有全部尝试),而且我在搜索中不止一次遇到过这个答案……在 Python 3 中,这个解决方案非常优雅,我相信它完全符合作者的要求,它更新了同一行中的单个语句。注意,如果行数缩短而不是增加,你可能需要做一些特殊处理(比如,将字符串设置为固定长度,并在末尾填充空格)。
if __name__ == '__main__':
for i in range(100):
print("", end=f"
PercentComplete: {i} %")
time.sleep(0.2)
解决方案 6:
对于控制台你可能需要
sys.stdout.flush()
强制更新。我认为,
在打印中使用会阻止标准输出刷新,因此无法更新
解决方案 7:
截至 2020 年底,对于我来说,Linux 控制台上的 Python 3.8.5 只有以下方法有效:
`print('some string', end='
')`
致谢:这篇文章
解决方案 8:
截至 2021 年,对于 Python 3.9.0,以下解决方案在 Windows 10、Pycharm 中对我有效。
`print('
some string ', end='', flush=True)`
解决方案 9:
如果您使用的是 Spyder,则所有上述解决方案都会连续打印这些行。避免这种情况的方法是使用:
for i in range(1000):
print('
' + str(round(i/len(df)*100,1)) + '% complete', end='')
sys.stdout.flush()
解决方案 10:
这对我来说很有用,我曾经破解过它以查看它是否可行,但从未在我的程序中实际使用过(GUI 好得多):
import time
f = '%4i %%'
len_to_clear = len(f)+1
clear = 'x08'* len_to_clear
print 'Progress in percent:'+' '*(len_to_clear),
for i in range(123):
print clear+f % (i*100//123),
time.sleep(0.4)
raw_input('
Done')
解决方案 11:
import time
import sys
def update_pct(w_str):
w_str = str(w_str)
sys.stdout.write("" * len(w_str))
sys.stdout.write(" " * len(w_str))
sys.stdout.write("" * len(w_str))
sys.stdout.write(w_str)
sys.stdout.flush()
for pct in range(0, 101):
update_pct("{n}%".format(n=str(pct)))
time.sleep(0.1)
会将光标的位置向后移动一个空格,
因此我们将其一直移回行首,
然后我们输入空格以清除当前行 - 当我们输入空格时,光标会向前/向右移动一个空格,
因此我们必须将光标移回行首,然后再写入新数据
使用 Python 2.7 在 Windows cmd 上测试
解决方案 12:
在这些情况下,使用 python 3.x,我使用以下代码:
for ii in range(100):
print(f"
Percent: {ii+1} %", end=" "*20)
其他一些答案的问题是,如果打印的字符串在一步中变短,则前一个字符串的最后一个字符将不会被覆盖。
所以我使用end=" "*20
in order 来用空格覆盖前一行。只需确保它20
比最长字符串的长度长即可。
解决方案 13:
尝试这样做:
for i in some_list:
#do a bunch of stuff.
print i/len(some_list)*100," percent complete",
(末尾有一个逗号。)
解决方案 14:
对于 Python 3+
for i in range(5):
print(str(i) + '
', sep='', end ='', file = sys.stdout , flush = False)
解决方案 15:
根据Remi 的回答使用Python 2.7+
如下:
from __future__ import print_function
import time
# status generator
def range_with_status(total):
""" iterate from 0 to total and show progress in console """
import sys
n = 0
while n < total:
done = '#' * (n + 1)
todo = '-' * (total - n - 1)
s = '<{0}>'.format(done + todo)
if not todo:
s += '
'
if n > 0:
s = '
' + s
print(s, end='
')
sys.stdout.flush()
yield n
n += 1
# example for use of status generator
for i in range_with_status(50):
time.sleep(0.2)
解决方案 16:
对于Python 3.6+
任何而list
不仅仅是int
s,以及使用控制台窗口的整个宽度并且不跨越到新行,您可以使用以下命令:
注意:请注意,该功能get_console_with()
仅在基于 Linux 的系统上运行,因此您必须重写它才能在 Windows 上运行。
import os
import time
def get_console_width():
"""Returns the width of console.
NOTE: The below implementation works only on Linux-based operating systems.
If you wish to use it on another OS, please make sure to modify it appropriately.
"""
return int(os.popen('stty size', 'r').read().split()[1])
def range_with_progress(list_of_elements):
"""Iterate through list with a progress bar shown in console."""
# Get the total number of elements of the given list.
total = len(list_of_elements)
# Get the width of currently used console. Subtract 2 from the value for the
# edge characters "[" and "]"
max_width = get_console_width() - 2
# Start iterating over the list.
for index, element in enumerate(list_of_elements):
# Compute how many characters should be printed as "done". It is simply
# a percentage of work done multiplied by the width of the console. That
# is: if we're on element 50 out of 100, that means we're 50% done, or
# 0.5, and we should mark half of the entire console as "done".
done = int(index / total * max_width)
# Whatever is left, should be printed as "unfinished"
remaining = max_width - done
# Print to the console.
print(f'[{done * "#"}{remaining * "."}]', end='
')
# yield the element to work with it
yield element
# Finally, print the full line. If you wish, you can also print whitespace
# so that the progress bar disappears once you are done. In that case do not
# forget to add the "end" parameter to print function.
print(f'[{max_width * "#"}]')
if __name__ == '__main__':
list_of_elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for e in range_with_progress(list_of_elements):
time.sleep(0.2)
解决方案 17:
如果您正在使用 Python 3,那么这适合您并且它确实有效。
print(value , sep='',end ='', file = sys.stdout , flush = False)
解决方案 18:
我自己刚刚想出了显示倒计时的方法,但它也可以用于百分比。
import time
#Number of seconds to wait
i=15
#Until seconds has reached zero
while i > -1:
#Ensure string overwrites the previous line by adding spaces at end
print("
{} seconds left. ".format(i),end='')
time.sleep(1)
i-=1
print("") #Adds newline after it's done
只要 '/r' 后面的内容与前一个字符串长度相同或更长(包括空格),它就会在同一行覆盖前一个字符串。请确保包含 end='' ,否则它会打印到换行符。希望对您有所帮助!
解决方案 19:
对于提供 StartRunning()、StopRunning()、boolean getIsRunning() 和整数 getProgress100() 的对象“pega”,返回 0 到 100 范围内的值,这在运行时提供文本进度条...
now = time.time()
timeout = now + 30.0
last_progress = -1
pega.StartRunning()
while now < timeout and pega.getIsRunning():
time.sleep(0.5)
now = time.time()
progress = pega.getTubProgress100()
if progress != last_progress:
print('
'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
last_progress = progress
pega.StopRunning()
progress = pega.getTubProgress100()
print('
'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)
扫码咨询,免费领取项目管理大礼包!