LoginSignup
4
4

More than 5 years have passed since last update.

CLIでプログレスを表示

Posted at

毎回どうやるんだっけかなーと調べてしまうのでメモ

4C3D7C50-0A61-4B6C-9F2B-AD7B15A96ED2-683-0000713D9E659AC0.gif

progress.rb
puts 'start'

list = (0..100).to_a
total = list.size
list.each.with_index(1) do |_v, i|
  print "progress... #{(i.to_f / total * 100).round}%\r" if $stdout.tty?
  sleep 0.01
end
puts ''

puts 'done'

やってること

  • $stdout.tty?
    • 端末から直接実行時にプログレスを表示
    • ruby progress.rb | less とかするとプログレスは表示しない
  • print\r
    • carriage return カーソルを行頭に戻す文字コード
  • puts ''
    • \rでカーソルが先頭に移動してしまってるので改行
4
4
2

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
4
4