Progress bar in python curses

我的梦境 提交于 2019-12-11 05:54:10

问题


I have created a progress bar which updates itself after getting a percentage from another function but I'm having issues getting it to trail like this ############. Instead, it just move the '#' to the right until 100% is reached. Below is my code. The reason why it's this way is because I need the percentage to come externally so that the code can be reusable. please help me.

import curses
import time

curses.initscr()

def percentage():
    loading = 0
    while loading < 100:
        loading += 1
        time.sleep(0.03)
        update_progress(loading)


def update_progress(progress):
    win = curses.newwin(3, 32, 3, 30)
    win.border(0)
    rangex = (30 / float(100)) * progress
    pos = int(rangex)
    display = '#'
    if pos != 0:
        win.addstr(1, pos, "{}".format(display))
        win.refresh()

percentage()

回答1:


you can just switch the pos to multiply the display #:

if pos != 0:
    win.addstr(1, 1, "{}".format(display*pos))
    win.refresh()



回答2:


The problem is that you call newwin() every time, discarding the old win and replacing it with a new one in the same place. That new window only gets one character added to it, with the background being blank, so you see an advancing cursor instead of a bar.

One possible solution:

import curses
import time

curses.initscr()

def percentage():
    win = curses.newwin(3, 32, 3, 30)
    win.border(0)
    loading = 0
    while loading < 100:
        loading += 1
        time.sleep(0.03)
        update_progress(win, loading)

def update_progress(win, progress):
    rangex = (30 / float(100)) * progress
    pos = int(rangex)
    display = '#'
    if pos != 0:
        win.addstr(1, pos, "{}".format(display))
        win.refresh()

percentage()

curses.endwin()

(Note the addition of a call to endwin() to restore the terminal to its normal mode.)

As far as leaving it onscreen after the program finishes, that's kind of outside the scope of curses. You can't really depend on any interaction between curses and stdio, sorry.



来源:https://stackoverflow.com/questions/46011314/progress-bar-in-python-curses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!