python 诅咒中的进度条

Progress bar in python curses

我创建了一个进度条,该进度条在从另一个函数获取百分比后自行更新,但我在让它像这样拖尾时遇到问题############。相反,它只是将“#”向右移动,直到达到 100%。下面是我的代码。之所以这样,是因为我需要百分比从外部来,这样代码才可以重用。请帮助我。

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()

您只需切换 pos 即可乘以 display #:

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

问题是你每次都调用newwin(),丢弃旧的win并在同一个地方用新的替换它。那个新的 window 只添加了一个字符,背景是空白的,所以你看到一个前进的光标而不是一个条。

一种可能的解决方案:

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()

(注意添加了对 endwin() 的调用以将终端恢复到正常模式。)

至于在程序完成后将其留在屏幕上,这有点超出了诅咒的范围。抱歉,您不能真正依赖 curses 和 stdio 之间的任何交互。