在控制台中打印ASCII旋转"光标"

pet*_*ter 13 ruby command-line progress

我有一个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"
}
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 35

是的,这适用于Windows,OS X和Linux.改进尼克拉斯的建议,你可以这样更普遍:

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)
Run Code Online (Sandbox Code Playgroud)

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

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!"
Run Code Online (Sandbox Code Playgroud)

这个输出:

Doing something tricky...|
Doing something tricky.../
Doing something tricky...-
Doing something tricky...\ 
(et cetera)
Doing something tricky...done!
Run Code Online (Sandbox Code Playgroud)

  • 很酷结合[关于SO的这个问题](http://stackoverflow.com/questions/2685435/cooler-ascii-spinners)得到微调字符和[这一个](http://stackoverflow.com/questions/17324656/ how-do-i-type-any-unicode-character-into-sublime-text)来查找Unicode字符.我知道它不是ASCII,但它很酷,因为许多人现在拥有Unicode终端 (2认同)

小智 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
Run Code Online (Sandbox Code Playgroud)

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

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

spin_it 10
Run Code Online (Sandbox Code Playgroud)