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

后端 未结 2 2033
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2021-01-06 16:30

    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
    
    0 讨论(0)
提交回复
热议问题