【问题标题】:How to output to the same line overwriting the previous line?输出到同一行覆盖前一个
【发布时间】:2014-12-22 10:07:03
【问题描述】:

如何通过 NTP 服务器覆盖之前接收到的计时(倒计时)来获得同一行的输出。如下图所示,每隔一秒定时在下一行接收。

13:35:01

13:35:00

13:34:59

13:34:58

13:34:57

13:34:56

我希望在清除前一个的同一行中收到计时。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以use the "return"-character \r to return to the beginning of the line。在 Python 2.x 中,您必须使用 sys.stdout.writesys.stdout.flush 而不是 print

    import time, sys
    while True:
        sys.stdout.write("\r" + time.ctime())
        sys.stdout.flush()
        time.sleep(1)
    

    在 Python 3.3 中,您可以使用 print 函数,并带有 endflush 参数:

        print(time.ctime(), end="\r", flush=True)
    

    但是请注意,这种方式只能替换屏幕上的最后一行。如果您想在更复杂的仅限控制台的 UI 中使用“实时”时钟,您应该查看curses

    import time, curses
    scr = curses.initscr()
    scr.addstr(0, 0, "Current Time:")
    scr.addstr(2, 0, "Hello World!")
    while True:
        scr.addstr(0, 20, time.ctime())
        scr.refresh()
        time.sleep(1)
    curses.endwin()
    

    【讨论】:

    • 不错!但是,执行此操作后,即使我在终端中输入,该行也不会跳过。
    • curses.endwin() 解决了这个问题。
    【解决方案2】:

    我正在使用 python 2.7

    python --version
    Python 2.7.12 :: Anaconda 4.1.1 (64-bit)
    

    我使用下面的函数作为一个钩子来显示下载进度,通过使用 urllib.urlretrieve

    def hook(bcount , bsize, tsize ):
        str = "[ %3d%% of %10d] \r" % (bcount * bsize * 100/tsize , tsize)    
        print str,
    
    urllib.urlretrieve (url, file_name, hook)
    

    说明: \r 将光标放在行首,逗号避免在新行中打印,如果每次打印的字符数相同,则可以解决问题

    如果您对 urllib 和我正在使用的钩子感到好奇,您会找到文档 https://docs.python.org/2/library/urllib.html

    【讨论】:

      【解决方案3】:

      这将像冠军一样工作:

      print("This text is about to vanish - from first line", end='')
      print("\rSame line output by Thirumalai")
      

      输出:

      Thirumalai 从第一行输出的同一行

      【讨论】:

      • 没有 Windows 10 IDLE 的 Python 3.8!
      • 我在 PowerShell 中使用 python test.py 运行脚本时得到了相同的结果,但在 ipython 或 python REPL 中没有。
      【解决方案4】:

      在 python3 中工作

      但仅适用于窗户

      import os
      import time
      while True:
          print(time.ctime())
          time.sleep(1)
          os.system('cls')
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 2017-04-07
        • 2010-11-17
        • 2015-03-14
        • 1970-01-01
        相关资源
        最近更新 更多