How to reset cursor to the beginning of the same line in Python

后端 未结 6 1292
暖寄归人
暖寄归人 2020-12-05 06:48

Most of questions related to this topics here in SO is as follows:

How to print some information on the same line without introducing a new line

6条回答
  •  伪装坚强ぢ
    2020-12-05 07:11

    On linux( and probably on windows) you can use curses module like this

    import time
    import curses
    
    win = curses.initscr()
    for i in range(100):
        win.clear()
        win.addstr("You have finished %d%%"%i)
        win.refresh()
        time.sleep(.1)
    curses.endwin()
    

    Benfit with curses as apposed to other simpler technique is that, you can draw on terminal like a graphics program, because curses provides moving to any x,y position e.g. below is a simple script which updates four views

    import time
    import curses
    
    curses.initscr()
    
    rows = 10
    cols= 30
    winlist = []
    for r in range(2):
        for c in range(2):
            win = curses.newwin(rows, cols, r*rows, c*cols)
            win.clear()
            win.border()
            winlist.append(win)
    
    for i in range(100):
        for win in winlist:
            win.addstr(5,5,"You have finished - %d%%"%i)
            win.refresh()
        time.sleep(.05)
    curses.endwin()
    

提交回复
热议问题