打印ASCII旋转“光标”在控制台 [英] Printing an ASCII spinning "cursor" in the console

查看:601
本文介绍了打印ASCII旋转“光标”在控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ruby脚本,做一些长时间的工作。它只是命令行,我想表明脚本仍在运行,而不是停止。我过去喜欢所谓的旋转光标在过去的日子,我设法在Windows下重现它的Ruby。

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?

没有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"
}


推荐答案

是的,这适用于Windows,OS X和Linux。改进尼克拉斯的建议,你可以使这更一般如下:

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

这个输出:

Doing something tricky...|
Doing something tricky.../
Doing something tricky...-
Doing something tricky...\ 
(et cetera)
Doing something tricky...done!

这篇关于打印ASCII旋转“光标”在控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆