Print in one line dynamically

后端 未结 20 3239
梦谈多话
梦谈多话 2020-11-21 23:32

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for it         


        
20条回答
  •  無奈伤痛
    2020-11-22 00:03

    Like the other examples,
    I use a similar approach but instead of spending time calculating out the last output length, etc,

    I simply use ANSI code escapes to move back to the beginning of the line and then clear that entire line before printing my current status output.

    import sys
    
    class Printer():
        """Print things to stdout on one line dynamically"""
        def __init__(self,data):
            sys.stdout.write("\r\x1b[K"+data.__str__())
            sys.stdout.flush()
    

    To use in your iteration loop you would just call something like:

    x = 1
    for f in fileList:
        ProcessFile(f)
        output = "File number %d completed." % x
        Printer(output)
        x += 1   
    

    See more here

提交回复
热议问题