6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プログレスバー表示させたいなぁ

Last updated at Posted at 2013-01-17

脈略もなく、タイトルのようなことを朝起きて断水してたしそういやどうすりゃいいんだろうなぁと思ってググったらStackOverflowに色々と書かれていた

その投稿されている中から、この投稿が他のライブラリ依存してないし、flushして書き換えしてるだけだからシンプルだなぁと思ったので参考にさせてもらった。
なんかこれだと100%表示されないし、どうなのかなぁと思ったのでちょっと改善。
といっても終了時に100%とするように修正しただけだけど。

# !/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import time
from random import random

def progress_bar(label, end_val, bar_length=40, slug='#', space=' '):
    def writing_bar(label, bar, percent):
        sys.stdout.write("\r{label}: [{bar}] {percent}%".format(
            label=label, bar=bar, percent=percent
        ))
        sys.stdout.flush()

    for i in range(0, end_val):
        percent = float(i) / end_val
        slugs = slug * int(round(percent * bar_length))
        spaces = space * (bar_length - len(slugs))
        # Some processing...
        # Is provisional
        time.sleep(random() * 0.1)
        writing_bar(label, slugs + spaces, int(round(percent * 100)))
    writing_bar(label, slugs + spaces, 100)
    sys.stdout.write('\n')

if __name__ == '__main__':
    progress_bar("Processing", 100)

time.sleepの部分が処理になるわけで、これを適宜置き換えるか、
それともprogress_barそのものをdecoratorにしてしまうとか、
そうしないと普通には使い物にならない。といってもプログレスバーというのは
cliアプリケーションにおいてwgetやらcurl -Oやら、なんというか
ネット上のリソースを得るもんだしそんなに考えなくてもいいもんなんだろうなぁ...?

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?