Printing an ASCII spinning “cursor” in the console

2020-02-08 08:25发布

I have a Ruby script that does some long taking jobs. It is command-line only and I would like to show that the script is still running and not halted. I used to like the so called "spinning cursor" in the old days and I managed to reproduce it in Ruby under Windows.

Question: does this work in the other OS's? If not, is there an OS-independent way to accomplish this?

No IRB solutions please.

10.times {
  print "/"
  sleep(0.1)
  print "\b"
  print "-"
  sleep(0.1)
  print "\b"
  print "\\"
  sleep(0.1)
  print "\b"
  print "|"
  sleep(0.1)
  print "\b"
}

3条回答
小情绪 Triste *
2楼-- · 2020-02-08 08:48

I wrote a gem spin_to_win that displays a spinner while yielding a block. For example:

SpinToWin.with_spinner('Zzzz') do |spinner| 
  spinner.banner('sleepy')
  sleep 1 
end
Zzzz \ [sleepy]

It can also track work pending vs. work completed:

SpinToWin.with_spinner('Zzzz') do |spinner|
    spinner.increment_todo!(3)

    spinner.banner('snore')
    sleep 1
    spinner.increment_done!

    spinner.banner('dream')
    sleep 1
    spinner.increment_done!

    spinner.banner('wake up!')
    sleep 1
    spinner.increment_done!
end
Zzzz \ 3 of 3 [wake up!]
查看更多
男人必须洒脱
3楼-- · 2020-02-08 08:50
# First define your chars
pinwheel = %w{| / - \\}

# Rotate and print as often as needed to "spin"
def spin_it
  print "\b" + pinwheel.rotate!.first
end

EDIT from peter: here a working version

def spin_it(times)
  pinwheel = %w{| / - \\}
  times.times do
    print "\b" + pinwheel.rotate!.first
    sleep(0.1)
  end
end

spin_it 10
查看更多
SAY GOODBYE
4楼-- · 2020-02-08 08:59

Yes, this works on Windows, OS X, and Linux. Improving on Niklas' suggestion, you can make this more general like so:

def show_wait_cursor(seconds,fps=10)
  chars = %w[| / - \\]
  delay = 1.0/fps
  (seconds*fps).round.times{ |i|
    print chars[i % chars.length]
    sleep delay
    print "\b"
  }
end

show_wait_cursor(3)

If you don't know how long the process will take, you can do this in another thread:

def show_wait_spinner(fps=10)
  chars = %w[| / - \\]
  delay = 1.0/fps
  iter = 0
  spinner = Thread.new do
    while iter do  # Keep spinning until told otherwise
      print chars[(iter+=1) % chars.length]
      sleep delay
      print "\b"
    end
  end
  yield.tap{       # After yielding to the block, save the return value
    iter = false   # Tell the thread to exit, cleaning up after itself…
    spinner.join   # …and wait for it to do so.
  }                # Use the block's return value as the method's
end

print "Doing something tricky..."
show_wait_spinner{
  sleep rand(4)+2 # Simulate a task taking an unknown amount of time
}
puts "Done!"

This one outputs:

Doing something tricky...|
Doing something tricky.../
Doing something tricky...-
Doing something tricky...\ 
(et cetera)
Doing something tricky...done!
查看更多
登录 后发表回答