14

我有一个 Ruby 脚本,它做了一些耗时的工作。它只是命令行,我想表明脚本仍在运行并且没有停止。在过去,我曾经喜欢所谓的“旋转光标”,我设法在 Windows 下的 Ruby 中重现了它。

问题:这在其他操作系统中是否有效?如果没有,是否有独立于操作系统的方法来实现这一点?

请不要 IRB 解决方案。

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

3 回答 3

35

是的,这适用于 Windows、OS X 和 Linux。改进 Niklas 的建议,您可以使这个更通用,如下所示:

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)

如果您不知道该过程需要多长时间,您可以在另一个线程中执行此操作:

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!"

这个输出:

Doing something tricky...|
Doing something tricky.../
Doing something tricky...-
Doing something tricky...\ 
(et cetera)
Doing something tricky...done!
于 2012-04-21T21:52:57.503 回答
6
# First define your chars
pinwheel = %w{| / - \\}

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

彼得编辑:这里是一个工作版本

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

spin_it 10
于 2012-06-01T15:24:49.460 回答
3

我写了一个 gem spin_to_win,它在产生一个块的同时显示一个微调器。例如:

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

它还可以跟踪待处理的工作与已完成的工作:

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!]
于 2016-03-06T04:01:18.017 回答