繁体   English   中英

如何在Python控制台应用程序中创建不确定的进度栏?

[英]How can I make an indeterminate progress bar in a Python console app?

我正在用Python重新编写一个C#控制台应用程序,我想移植一个不确定的基于控制台的进度条类。

我有使用文本创建确定进度条的示例,但是我不确定如何处理不确定的进度条。 我假设我需要某种线程。 谢谢你的帮助!

这是课程:

public class Progress {
    String _status = "";
    Thread t = null;

    public Progress(String status) {
        _status = status;
    }

    public Progress Start() {
        t = new Thread(() => {
            Console.Write(_status + "    ");

            while (true) {
                Thread.Sleep(300);
                Console.Write("\r" + _status + "    ");
                Thread.Sleep(300);
                Console.Write("\r" + _status + " .  ");
                Thread.Sleep(300);
                Console.Write("\r" + _status + " .. ");
                Thread.Sleep(300);
                Console.Write("\r" + _status + " ...");
            }
        });

        t.Start();

        return this;
    }

    public void Stop(Boolean appendLine = false) {
        t.Abort();
        Console.Write("\r" + _status + " ... ");
        if (appendLine)
            Console.WriteLine();
    }

}

PS随意参加该进步班)

import sys, time
while True:
    for i in range( 4 ):
        sys.stdout.write( '\r' + ( '.' * i ) + '   ' )
        sys.stdout.flush()
        time.sleep( 0.5 )

那在命令行上做动画。 这里应该有足够的Python线程示例。

编辑:

可能的线程解决方案; 不知道写一个真实的线程是否会更有效,因为我不使用python太多线程.. from threading import Timer import sys,time

def animation ( i = 0 ):
    sys.stdout.write( '\r' + ( '.' * i ) + '   ' )
    sys.stdout.flush()
    Timer( 0.5, animation, ( 0 if i == 3 else i + 1, ) ).start()

animation()
print( 'started!' )

while True:
    pass

我已经在Python中实现了类似的功能。 看一下并根据需要进行修改:

class ProgressBar(object):

    def __init__(self, min_val=0, max_val=100, width=30, stdout=sys.stdout):
        self._progress_bar = '[]'   # holds the progress bar string
        self._old_progress_bar = '[]'

        self.min = min_val
        self.max = max_val
        self.span = max_val - min_val
        self.width = width
        self.current = 0            # holds current progress value
        self.stdout = stdout

        self.update(min_val)        # builds the progress bar string

    def increment(self, incr):
        self.update(self.current + incr)

    def update(self, val):
        """Rebuild the progress bar string with the given progress
        value as reference.

        """
        # cap the value at [min, max]
        if val < self.min: val = self.min
        if val > self.max: val = self.max
        self.current = val 

        # calculate percentage done
        diff = self.current - self.min
        done = int(round((float(diff) / float(self.span)) * 100.0))

        # calculate corresponding number of filled spaces
        full = self.width - 2 
        filled = int(round((done / 100.0) * full))

        # build the bar
        self._progress_bar = '[%s>%s] %d%%' % \ 
          ('=' * (filled - 1), ' ' * (full - filled), done)

    def draw(self, padding=0):
        """Draw the progress bar to current line in stdout.

        """
        if self._old_progress_bar != self._progress_bar:
            self._old_progress_bar = self._progress_bar
            self.stdout.write('\r%s%s ' % 
              (' ' * padding, self._progress_bar))
            self.stdout.flush()      # force stdout update

    def close(self):
        """Finish the progress bar. Append a newline and close
        stdout handle.

        """
        self.stdout.write('\n')
        self.stdout.flush()

    def __str__(self):
        return self._progress_bar

用法示例:

def reporter(count, size, total):
    """The reporthook callback."""
    if self._progbar is None:
        self._progbar = ProgressBar(max_val=total)

    self._progbar.increment(size)
    self._progbar.draw(padding=3)

try:
    message = 'Begin downloading %s to %s' % (self.url, self.to)
    LOGGER.debug(message)
    print message
    filename, headers = urllib.urlretrieve(self.url, self.to, reporter)
    print 'Download finished.'
except:
    LOGGER.exception('Download interrupted: %s' % sys.exc_info()[0])
finally:
    self._progbar.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM