在python中,打印到相同的行而不是新的行

时间:2021-06-19 00:05:56

Basically I want to do the opposite of what this guy did... hehe.

基本上我想做和这个人做的相反的事。呵呵。

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

Python脚本:每次打印新行到shell,而不是更新现有行

I have a program that is telling me how far along it is.

我有一个程序告诉我它有多远。

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

So if len(some_list) was 50, I'd get that last line printed 50 times over. I want to print one line and keep updating that line. I know I know this is probably the lamest question you'll read all day. I just can't figure out the four words I need to put into google to get the answer.

如果len(some_list)是50,最后一行会打印50次。我想打印一行,并不断更新这一行。我知道我知道这可能是你整天读到的最糟糕的问题。我就是想不出我需要在谷歌中输入的四个词来得到答案。

Update! I tried mvds' suggestion which SEEMED right. The new code

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

print percent_complete,"           \r",

Percent complete is just a string (I was abstracting the first time now I an trying to be literal). The result now is that it runs the program, doesn't print ANYTHING until after the program is over, and then prints "100 percent complete" on one and only one line.

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

Without the carriage return (but with the comma, half of mvds' suggestion) it prints nothing until the end. And then prints:

没有回车(但是用逗号,mvds的建议的一半),它会一直打印到最后。然后打印:

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

And so on. So now the new issue is that with the comma it doesn't print until the program is finished.

等等。现在的新问题是用逗号直到程序完成才打印。

With the carriage return and no comma it behaves the exact same as with neither.

对于回车和不带逗号的回车,它的行为与两者都不带的情况完全相同。

9 个解决方案

#1


68  

It's called the carriage return, or \r

它被称为回车,或\r

Use

使用

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

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

逗号可以防止打印添加新行。(空格将保留之前输出的线)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

另外,不要忘记用一个打印“”来结束,以获得一个最终的换行!

#2


19  

From python 3.x you can do:

从python 3。x你能做什么:

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

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

(也可以在Python 2.6或2.7中使用,方法是将__future__导入print_function放在脚本/模块的顶部)

Python console progressbar example:

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)

#3


10  

For me, what worked was a combo of Remi's and siriusd's answers:

对我来说,是Remi和siriusd回答的组合:

from __future__ import print_function
import sys

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

#4


9  

for Console you'll probably need

对于控制台,您可能需要

sys.stdout.flush()

to force update. I think using , in print will block stdout from flushing and somehow it won't update

强制更新。我认为使用,in print会阻止stdout刷新,而且它不会更新

#5


2  

This works for me, hacked it once to see if it is possible, but never actually used in my program (GUI is so much nicer):

这对我来说是可行的,我把它砍了一次,看看是否有可能,但是我的程序从来没有使用过(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('\nDone')

#6


1  

Try it like this:

试试这样:

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

(With a comma at the end.)

(末尾有逗号。)

#7


1  

import time
import sys


def update_pct(w_str):
    w_str = str(w_str)
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(" " * len(w_str))
    sys.stdout.write("\b" * 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)

\b will move the location of the cursor back one space
So we move it back all the way to the beginning of the line
We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one
So then we have to move the cursor back at the beginning of the line before we write our new data

\ b将光标的位置一个空间我们移动它到线然后写空间的开始清除当前行——我们写空间光标向前/右一所以我们必须移动光标在一行的开始在我们写新数据

Tested on Windows cmd using Python 2.7

使用Python 2.7对Windows cmd进行测试。

#8


0  

Based on Remi answer for Python 2.7+ use this:

基于Python的Remi答案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 += '\n'
        if n > 0:
            s = '\r' + s
        print(s, end='\r')
        sys.stdout.flush()
        yield n
        n += 1


# example for use of status generator
for i in range_with_status(50):
    time.sleep(0.2)

#9


0  

Nobody has mentioned that in Python 3(.something?) you don't need sys.stdout.flush(). print('foobar', end='', flush=True) works.

在Python 3(.something?)中没有人提到过您不需要sys.stdout.flush()。打印(“foobar”,结束= ",冲洗= True)工作。

#1


68  

It's called the carriage return, or \r

它被称为回车,或\r

Use

使用

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

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

逗号可以防止打印添加新行。(空格将保留之前输出的线)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

另外,不要忘记用一个打印“”来结束,以获得一个最终的换行!

#2


19  

From python 3.x you can do:

从python 3。x你能做什么:

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

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

(也可以在Python 2.6或2.7中使用,方法是将__future__导入print_function放在脚本/模块的顶部)

Python console progressbar example:

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)

#3


10  

For me, what worked was a combo of Remi's and siriusd's answers:

对我来说,是Remi和siriusd回答的组合:

from __future__ import print_function
import sys

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

#4


9  

for Console you'll probably need

对于控制台,您可能需要

sys.stdout.flush()

to force update. I think using , in print will block stdout from flushing and somehow it won't update

强制更新。我认为使用,in print会阻止stdout刷新,而且它不会更新

#5


2  

This works for me, hacked it once to see if it is possible, but never actually used in my program (GUI is so much nicer):

这对我来说是可行的,我把它砍了一次,看看是否有可能,但是我的程序从来没有使用过(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('\nDone')

#6


1  

Try it like this:

试试这样:

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

(With a comma at the end.)

(末尾有逗号。)

#7


1  

import time
import sys


def update_pct(w_str):
    w_str = str(w_str)
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(" " * len(w_str))
    sys.stdout.write("\b" * 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)

\b will move the location of the cursor back one space
So we move it back all the way to the beginning of the line
We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one
So then we have to move the cursor back at the beginning of the line before we write our new data

\ b将光标的位置一个空间我们移动它到线然后写空间的开始清除当前行——我们写空间光标向前/右一所以我们必须移动光标在一行的开始在我们写新数据

Tested on Windows cmd using Python 2.7

使用Python 2.7对Windows cmd进行测试。

#8


0  

Based on Remi answer for Python 2.7+ use this:

基于Python的Remi答案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 += '\n'
        if n > 0:
            s = '\r' + s
        print(s, end='\r')
        sys.stdout.flush()
        yield n
        n += 1


# example for use of status generator
for i in range_with_status(50):
    time.sleep(0.2)

#9


0  

Nobody has mentioned that in Python 3(.something?) you don't need sys.stdout.flush(). print('foobar', end='', flush=True) works.

在Python 3(.something?)中没有人提到过您不需要sys.stdout.flush()。打印(“foobar”,结束= ",冲洗= True)工作。