LoginSignup
3
0

More than 3 years have passed since last update.

Nimでプログレスバー

Last updated at Posted at 2019-06-03

はじめに

ディレクトリ内の全ファイルを開いてごにょごにょするプログラムをよく書きます。
自分で使う分には気にしないのですが、人から依頼された場合は「親切かな」と思い進捗率を表示させています。
最近マンネリなのでちょっとリッチなプログレスバーを試してみました。

環境

  • windows10 home
  • nim 0.19.0

いつものプログレスバー

例えばこういうディレクトリのとき

- xxx/logs
 - 20190501.log
 - 20190502.log
 - 20190503.log
 - ...
 - 20190531.log

logs内のlogを開いてごにょごにょ、の進捗率はキャリッジリターンで表現しています

progress1.nim
import os, strformat

proc getFiles(dir: string): seq[string] =
   # walkDirRecでもいいかも
   for file in walkFiles(dir):
    result.add(file)

when isMainModule:
  let
    dir = "xxxx\\logs\\*.log"
    files = getFiles(dir)
    total= len(files)
  var done = 0
  for file in files:
    stdout.write(fmt"{$done} / {$total}")
    stdout.write("\r")  # キャリッジリターン(カーソルを左に戻す)
    # ごにょごにょ
    inc(done)
  stdout.write(fmt"{$done} / {$total}")
  stdout.write("\r\l")
  stdout.write("finish!!")

動かすとこうなります
progress1.gif

リッチなプログレスバー

矢印を使って進捗率を表現したらリッチになりますね
そんなときはprogressライブラリを使います

nimble install progress

さきほどのソースはprogressを使うとこうなります

progress2.nim
import os, strformat, progress

proc getFiles(dir: string): seq[string] =
  for file in walkFiles(dir):
    result.add(file)

when isMainModule:
  let
    dir = "xxxx\\logs\\*.log"
    files = getFiles(dir)
    total = len(files)
  var pb = newProgressBar(total = total) # totalは分母
  pb.start()
  for file in files:
    # ごにょごにょ
    pb.increment()  # 今回ディレクトリに6ファイルあるので (x / 6 * 100) % を表示
  pb.finish()

動かすとこうなります
progress2.gif

おわりに

ちょっとリッチになりましたね
え、プログレスバーより中身をリッチにしろ?
ほんそれ

3
0
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
3
0