我想从Ruby脚本启动并管理Linux上长时间运行(几个小时)的shell命令。 我需要能够逐行解析输出。不是在完成这个过程的时候。 如果我不喜欢输出,我需要能够终止命令并重新启动它。 我还需要知道这个过程是否会消失。
我找到了right_popen gem,但它已经2年没有更新,也没有文档。什么是最干净的方法呢?
答案 0 :(得分:0)
我找到了一个允许我完成上述所有工作的解决方案,所以我想我会跟那些跟我来的人分享:-) 我们通过伪终端来实现,这些伪终端在stdlib中(不需要宝石)。
以下是我需要的代码示例:
require 'pty'
cmd = 'for i in 1 2 3 4 5; do echo $i; sleep 1; done'
PTY.spawn cmd do |r, w, pid|
begin
r.sync
r.each_line do |l|
# Process each line immediately
line = l.strip
puts line
if line == '3'
# We kill the command on 3, because 3s are evil...
::Process.kill('SIGINT', pid)
end
end
rescue Errno::EIO => e
# Linux raises this error when the command ends
puts "COMMAND DIED"
ensure
# Wait for the process to end before we go on
::Process.wait pid
puts "WE ARE CLEAR"
end
end
输出:
1
2
3
COMMAND DIED
WE ARE CLEAR