How do I listen to STDIN input without pausing my script?

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

I have a while loop consistently listening to incoming connections and outputting them to console. I would like to be able to issue commands via the console without affecting the output. I've tried:

Thread.new do     while true         input   = gets.chomp         puts "So I herd u sed, \"#{input}\"."         #Commands would be in this scope     end end 

However, that seems to pause my entire script until input is received; and even then, some threads I have initiated before this one don't seem to execute. I've tried looking at TCPSocket's select() method to no avail.

回答1:

Not sure where are the commands you want to "continue running" in your example. Try this small script:

Thread.new do   loop do     s = gets.chomp     puts "You entered #{s}"     exit if s == 'end'   end end  i = 0 loop do   puts "And the script is still running (#{i})..."   i += 1   sleep 1 end 

Reading from STDIN is done in a separate thread, while the main script continues to work.



回答2:

Ruby uses green threads, so blocking system calls will block all threads anyway. An idea:

require 'io/wait'  while true   if $stdin.ready?     line = $stdin.readline.strip     p "line from stdin: #{line}"   end   p "really, I am working here"   sleep 0.1 end 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!