【问题标题】:How to refresh the multi-line output dynamically如何动态刷新多行输出
【发布时间】:2013-01-13 04:51:13
【问题描述】:

我想动态刷新一些信息(就像进度条一样),我可以用下面的代码来完成

#! /usr/bin/env python
import sys
import time

print "start the output"
def loop():
    i = 0

    while 1:
        i += 1
        output = "\rFirst_line%s..." % str(i) 
        sys.stdout.write(output)        
        sys.stdout.flush()
        time.sleep(1)
loop()

只能动态输出单行信息,当在输出中添加'\n'时,无法正常工作。

output = "\rFirst_line%s...\n" % str(i)

有什么办法可以帮助它刷新多行内容?

【问题讨论】:

    标签: python


    【解决方案1】:

    我也遇到过这种情况,终于有办法解决了;D

    reprint- A simple module for Python 2/3 to print and refresh multi line output contents in terminal

    您可以简单地将 output 实例视为普通的 dictlist(取决于您使用的模式)。当您在output 实例中修改该内容时,终端中的输出将自动刷新:D

    这是一个例子:

    from reprint import output
    import time
    import random
    
    print "start the output"
    
    with output(initial_len=3, interval=0) as output_lines:
        while True:
            output_lines[0] = "First_line  {}...".format(random.randint(1,10))
            output_lines[1] = "Second_line {}...".format(random.randint(1,10))
            output_lines[2] = "Third_line  {}...".format(random.randint(1,10))
            time.sleep(0.5)
    

    【讨论】:

      【解决方案2】:

      您可以使用 curses 来做到这一点,但这很重要。

      【讨论】:

        【解决方案3】:

        没有办法独立于系统(当说“系统”时,我指的不仅仅是操作系统,还包括终端应用程序及其设置),因为没有标准的转义序列可以向上移动光标。至于与系统相关的方式,它们可能存在于您的配置中,但需要有关您的系统的更多信息。而且无论如何,使用这些功能通常不是一个好主意。

        附:希望您不会将程序的输出重定向到文件。如果重定向到文件,这样的进度指示器会产生糟糕的输出。

        【讨论】:

          【解决方案4】:

          将 '\b' 写入控制台:

          import sys
          import time
          
          print "start the output"
          def loop():
              i = 0
              output = "\rFirst_line%s..." % str(0) 
              sys.stdout.write(output)
              while 1:
                  sys.stdout.write('\b'*len(output))
                  i += 1
                  output = "\rFirst_line%s..." % str(i) 
                  sys.stdout.write(output)        
                  sys.stdout.flush()
                  time.sleep(1)
          loop()
          

          【讨论】:

          • 嗨,imxylz。感谢您的快速响应,但是如果输出中有'\n',它仍然无法正常工作,例如 output = "\rFirst_line%s...\n+++" % str(i)。
          • 您不能用新行回写(退格),尽管 tt 可能看起来很合理,但以前不会向后兼容电传打字机。如果要清除所有屏幕,请选中此项。 stackoverflow.com/questions/3136202/…
          • 我尝试了新函数 print(object1,object2,sep='\n',end=''),然后是 sys.stdout.write('\b\b\b/b\ '),对于带有 '\n' 的字符串,'\b' 仍然不能正常工作。看来我必须改变我的方式(使用 os.system('clear')。再次感谢
          猜你喜欢
          • 1970-01-01
          • 2021-05-07
          • 2020-06-29
          • 1970-01-01
          • 2012-05-08
          • 2014-04-23
          • 2015-11-25
          • 2011-04-02
          • 2012-03-09
          相关资源
          最近更新 更多