How to listen to STDIN input without pausing my script?

I have a loop whilethat sequentially listens for incoming connections and outputs them to the console. I would like to be able to issue commands through the console without affecting the output. I 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, this seems to pause my entire script until input is received; and even then some of the threads that I initiated before this one seem to not be running. I tried looking at the TCPSocket method to select()no avail.

+3
source share
2 answers

Not sure where the commands you want to continue are in your example. Try this little 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 performed in a separate thread, and the main script continues to work.

+5

Ruby , . :

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
+2

Source: https://habr.com/ru/post/1785227/


All Articles