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

后端 未结 2 2051
天涯浪人
天涯浪人 2021-01-06 15:54

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 wit

2条回答
  •  日久生厌
    2021-01-06 16:29

    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.

提交回复
热议问题