如何在不暂停脚本的情况下收听 STDIN 输入? [英] How do I listen to STDIN input without pausing my script?

查看:51
本文介绍了如何在不暂停脚本的情况下收听 STDIN 输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 while 循环,持续监听传入的连接并将它们输出到控制台.我希望能够通过控制台发出命令而不影响输出.我试过了:

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

然而,这似乎暂停了我的整个脚本,直到收到输入;即便如此,我在此之前启动的一些线程似乎没有执行.我试过查看 TCPSocket 的 select() 方法无济于事.

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.

推荐答案

不确定示例中要继续运行"的命令在哪里.试试这个小脚本:

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

从 STDIN 读取是在一个单独的线程中完成的,而主脚本继续工作.

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

这篇关于如何在不暂停脚本的情况下收听 STDIN 输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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