在python中打印到同一行而不是新行

2024-05-23 23:24:30 发布

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

基本上我想做和这家伙相反的事。。。呵呵。

Python Script: Print new line each time to shell rather than update existing line

我有一个程序告诉我这段路有多远。

for i in some_list:
    #do a bunch of stuff.
    print i/len(some_list)*100," percent complete"

所以如果len(某个清单)是50,我会把最后一行打印50次。我想打印一行并不断更新。我知道这可能是你一整天都要读的最蹩脚的问题。我只是想不出我需要在google上输入的四个单词才能得到答案。

更新!我尝试了mvds的建议,似乎是对的。新代码

print percent_complete,"           \r",

完成百分比只是一个字符串(我是第一次抽象,现在我试图成为文字)。现在的结果是它运行程序,直到程序结束后才打印任何内容,然后在一行上打印“100%完成”。

如果没有回车符(但是有逗号,MVD建议的一半),它在结尾之前不会打印任何内容。然后打印:

0 percent complete     2 percent complete     3 percent complete     4 percent complete    

等等。所以现在的新问题是用逗号在程序完成之前不会打印。

在回车和无逗号的情况下,它的行为与两者都不相同。


Tags: 程序内容newlenlinescriptsome建议
3条回答

在Python3.x中,您可以执行以下操作:

print('bla bla', end='')

(也可以在Python2.6或2.7中使用,方法是将from __future__ import print_function放在脚本/模块的顶部)

Python控制台progressbar示例:

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+='\n'        
        if n>0:
            s = '\r'+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)

对我来说,有效的是雷米和西瑞乌德的答案的结合:

from __future__ import print_function
import sys

print(str, end='\r')
sys.stdout.flush()

它叫做回车,或者\r

使用

print i/len(some_list)*100," percent complete         \r",

逗号防止打印添加换行符。(这些空格将使行与先前的输出保持距离)

另外,不要忘记使用print ""终止,以获得至少一个定稿换行符!

相关问题 更多 >