Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印到同一行而不是新行?_Python_Stdout - Fatal编程技术网

Python 打印到同一行而不是新行?

Python 打印到同一行而不是新行?,python,stdout,Python,Stdout,基本上我想做和这家伙相反的事。。。呵呵 我有一个程序告诉我这条路有多远 for i in some_list: #do a bunch of stuff. print i/len(some_list)*100," percent complete" 所以如果len(some_list)是50,我会把最后一行打印50次。我想打印一行并不断更新那一行。我知道我知道这可能是你一整天都在读的最蹩脚的问题。我就是想不出我需要在谷歌上输入的四个词来得到答案 更新!我尝试了MVD的建议,这

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

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

for i in some_list:
    #do a bunch of stuff.
    print i/len(some_list)*100," percent complete"
所以如果len(some_list)是50,我会把最后一行打印50次。我想打印一行并不断更新那一行。我知道我知道这可能是你一整天都在读的最蹩脚的问题。我就是想不出我需要在谷歌上输入的四个词来得到答案

更新!我尝试了MVD的建议,这似乎是正确的。新代码

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

如果没有回车符(但是有逗号,mvds建议的一半),它将不打印任何内容,直到结束。然后打印:

0 percent complete     2 percent complete     3 percent complete     4 percent complete    
等等。所以现在的新问题是,在程序完成之前,逗号不会打印


有回车符且无逗号时,其行为与无逗号时完全相同。

称为回车符,或
\r

使用

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

另外,不要忘了使用
print”“
结束,以获得至少一个定稿换行

像这样试试:

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

(结尾有一个逗号。)

这对我来说很有效,对它进行了一次黑客攻击,看看它是否可行,但从未在我的程序中实际使用过(GUI非常好):


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

print('bla bla', end='')
(也可以在Python 2.6或2.7中使用,方法是将
from\uuuuuu future\uuuuu导入print\u函数
放在脚本/模块的顶部)

Python控制台progressbar示例:

导入时间
#状态发生器
def范围_和_状态(总计):
“”“从0迭代到总计,并在控制台中显示进度”“”
n=0
而n0:
s='\r'+s
打印,结束=“”)
产量
n+=1
#状态生成器的使用示例
对于处于范围内且状态为(10)的i:
睡眠时间(0.1)

对于您可能需要的控制台

sys.stdout.flush()

强制更新。我认为在打印中使用
会阻止stdout刷新,而且不知何故它不会更新对我来说,有效的方法是将Remi和siriusd的答案结合起来:

from __future__ import print_function
import sys

print(str, end='\r')
sys.stdout.flush()
\b
将光标位置向后移动一个空间
因此,我们将其一直向后移动到行的开头
然后,我们写入空格以清除当前行-在写入空格时,光标向前/向右移动一个
因此,在写入新数据之前,我们必须将光标移回行的开头

基于for
Python 2.7+
在Windows cmd上使用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 += '\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)
from\uuuuu future\uuuuu导入打印功能
导入时间
#状态发生器
def范围_和_状态(总计):
“”“从0迭代到总计,并在控制台中显示进度”“”
导入系统
n=0
而n0:
s='\r'+s
打印,结束='\r')
sys.stdout.flush()
产量
n+=1
#状态生成器的使用示例
对于处于范围内且状态为(50)的i:
睡眠时间(0.2)

在Python3.3+中,您不需要
sys.stdout.flush()
<代码>打印(字符串,结束='',刷新=真)有效

所以

print('foo',end='')
打印('\rbar',end='',flush=True)

将用“bar”覆盖“foo”。

对于
Python 3.6+
和任何
列表
,而不仅仅是
int
s,以及使用控制台窗口的整个宽度,而不是跨到新行,您可以使用以下选项:

注意:请注意,函数
get\u console\u with()
将仅在基于Linux的系统上工作,因此您必须重写它才能在Windows上工作

导入操作系统
导入时间
def get_控制台_宽度():
“”“返回控制台的宽度。
注意:以下实现仅适用于基于Linux的操作系统。
如果您希望在其他操作系统上使用它,请确保对其进行适当修改。
"""
返回int(os.popen('stty size','r').read().split()[1])
def范围和进度(元素列表):
“”“使用控制台中显示的进度条遍历列表。”“”
#获取给定列表的元素总数。
总计=长度(元素列表)
#获取当前使用的控制台的宽度。从该值中减去2
#边缘字符“[”和“]”
最大宽度=获取控制台宽度()-2
#开始迭代列表。
对于索引,枚举中的元素(元素列表):
#计算应打印为“完成”的字符数。这很简单
#所完成工作的百分比乘以控制台的宽度。那个
#is:如果我们是100分之50,那意味着我们完成了50%,或者
#0.5,我们应该将整个控制台的一半标记为“完成”。
完成=整数(索引/总*最大宽度)
#无论剩下什么,都应打印为“未完成”
剩余=最大宽度-完成
#打印到控制台。
打印(f'[{done*“#”}{remaining*“}]”,end='\r')
#让元素与它一起工作
屈服要素
#最后,打印整行。如果愿意,还可以打印空白
#这样,一旦完成,进度条就会消失。在那种情况下,不要这样做
#忘记在打印函数中添加“end”参数。
打印(f'[{max_width*“#“}]”)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
元素列表=['a'、'b'、'c'、'd'、'e'、'f'、'g'、'h'、'i'、'j']
对于具有进度的范围内的e(元素列表):
睡眠时间(0.2)

比赛迟到了-但因为没有
sys.stdout.flush()
from __future__ import print_function
import sys

print(str, end='\r')
sys.stdout.flush()
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)
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)
if __name__ == '__main__':
    for i in range(100):
        print("", end=f"\rPercentComplete: {i} %")
        time.sleep(0.2)
print(value , sep='',end ='', file = sys.stdout , flush = False)
for i in range(1000):
    print('\r' + str(round(i/len(df)*100,1)) + '% complete', end='')
    sys.stdout.flush()
for i in range(5):
    print(str(i) + '\r', sep='', end ='', file = sys.stdout , flush = False)
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("\r{} seconds left.   ".format(i),end='')
        time.sleep(1)
        i-=1
    print("") #Adds newline after it's done
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('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
        last_progress = progress

pega.StopRunning()

progress = pega.getTubProgress100()
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)