Output to the same line overwriting previous

前端 未结 4 665
醉话见心
醉话见心 2020-11-27 06:02

how to get output to the same line by overwriting previous received Timing(countdown) by NTP server. As shown below after each second timing is receiving in next row.

<
4条回答
  •  Happy的楠姐
    2020-11-27 07:04

    You can use the "return"-character \r to return to the beginning of the line. In Python 2.x, you'll have to use sys.stdout.write and sys.stdout.flush instead of print.

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

    In Python 3.3, you can use the print function, with end and flush parameters:

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

    Note, however, that this way you can only replace the last line on the screen. If you want to have a "live" clock in a more complex console-only UI, you should check out 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)
    

提交回复
热议问题