代码之家  ›  专栏  ›  技术社区  ›  chriscauley

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

  •  57
  • chriscauley  · 技术社区  · 15 年前

    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次。我想打印一行并不断更新那一行。我知道这可能是你一整天都在读的最蹩脚的问题了。我就是想不出要在谷歌上输入四个词才能得到答案。

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

    print percent_complete,"           \r",
    

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

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

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

    9 回复  |  直到 5 年前
        1
  •  88
  •   mvds    15 年前

    这叫马车返回,或者 \r

    使用

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

    逗号防止print添加换行符(空格将保持线与先前输出的距离)

    另外,别忘了用 print "" 至少有一个定稿的新词!

        2
  •  34
  •   Remi    14 年前

    在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)
    
        3
  •  34
  •   dlchambers    10 年前

    对我来说,有效的是雷米和西利乌斯的答案:

    from __future__ import print_function
    import sys
    
    print(str, end='\r')
    sys.stdout.flush()
    
        4
  •  24
  •   LeopardShark    5 年前

    在python3.3+中,您不需要 sys.stdout.flush() . print(string, end='', flush=True) 作品。

    所以呢

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

    将用bar覆盖foo。

        5
  •  13
  •   siriusd    13 年前

    您可能需要的控制台

    sys.stdout.flush()
    

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

        6
  •  5
  •   SteveJ    6 年前

    游戏进行得太晚了-但是由于没有一个答案对我有效(我没有全部尝试),而且我在搜索中不止一次遇到这个答案。。。在python3中,这个解决方案非常优雅,我相信它完全符合作者的要求,它在同一行上更新了一条语句。请注意,如果线收缩而不是增长,则可能需要做一些特殊的操作(例如,可能使字符串具有固定长度,并在末尾填充空格)

    if __name__ == '__main__':
        for i in range(100):
            print("", end=f"\rPercentComplete: {i} %")
            time.sleep(0.2)
    
        7
  •  3
  •   Tony Veijalainen    15 年前

    这对我来说很有用,曾对它进行过一次黑客攻击,看看它是否可行,但从未在我的程序中实际使用过(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')
    
        8
  •  2
  •   Robert    9 年前
    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 将光标的位置移回一个空格
    所以我们把它一直移到线的开头
    然后我们写空格来清除当前行-当我们写空格时,光标向前/向右移动1
    因此,在写入新数据之前,我们必须将光标移回行的开头

    使用python2.7在Windows cmd上测试

        9
  •  2
  •   rroger    5 年前

    到2020年底,linux控制台上的Python 3.8.5对我来说只起作用:

    print('some string', end='\r')

    贷方为: This post

        10
  •  1
  •   chryss    15 年前

    试着这样做:

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

    (结尾有逗号)

        11
  •  1
  •   bfree67    6 年前

    如果您使用的是Spyder,则这些行只需使用以前的所有解决方案连续打印即可。避免这种情况的方法是:

    for i in range(1000):
        print('\r' + str(round(i/len(df)*100,1)) + '% complete', end='')
        sys.stdout.flush()
    
        12
  •  1
  •   maximusdooku    6 年前

    对于Python 3+

    for i in range(5):
        print(str(i) + '\r', sep='', end ='', file = sys.stdout , flush = False)
    
        13
  •  0
  •   Francisco Costa    8 年前

    基于 Remi answer 对于 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)
    
        14
  •  0
  •   tamaroth    7 年前

    为了 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='\r')
            # 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)
    
    
        15
  •  0
  •   Azaz-ul- Haque    6 年前

    如果您使用的是Python3 这是给你的,真的很管用。

    print(value , sep='',end ='', file = sys.stdout , flush = False)
    
        16
  •  0
  •   ReconGator    6 年前

    只是我自己想出来的倒计时,但它也会工作的百分比。

    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
    

    只要'/r'后面的字符串长度与前一个字符串相同或更长(包括空格),它就会在同一行上覆盖它。只需确保包含end='',否则它将打印成换行符。希望有帮助!

        17
  •  0
  •   jwasch    5 年前

    对于提供StartRunning()、StopRunning()的对象“pega”, boolean getIsRunning()和integer getProgress100()返回 值的范围为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('\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)
    
        18
  •  0
  •   Rujuta Vaze    5 年前

    print('\r some string ', end='', flush=True)

    推荐文章