这是带有可选标准输入数据的实时标准输出的片段。您需要使用IO.select
来查看流以查看它们是否可读。
require 'open3'
class Runner
class Result
attr_accessor :status
attr_reader :stdout, :stderr
def initialize
@stdout = +''
@stderr = +''
@status = -127
end
def success?
status.zero?
end
end
attr_reader :result
def initialize(cmd, stdin: nil, print_to: nil)
@stdin = stdin
@cmd = cmd
@result = Result.new
@print_to = print_to
end
def run
Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr|
# Dump the stdin-data into the command's stdin:
unless stdin.closed?
stdin.write(@stdin) if @stdin
stdin.close
end
until [stdout, stderr].all?(&:eof?)
readable = IO.select([stdout, stderr])
next unless readable&.first
readable.first.each do |stream|
data = +''
begin
stream.read_nonblock(1024, data)
rescue EOFError
# ignore, it's expected for read_nonblock to raise EOFError
# when all is read
end
next if data.empty?
if stream == stdout
result.stdout << data
@print_to << data if @print_to
else
result.stderr << data
@print_to << data if @print_to
end
end
end
result.status = wait_thr.value.exitstatus
end
result
end
end
result = Runner.new('ls -al').run
puts "Exit status: %d" % result.status
puts "Stdout:"
puts result.stdout
puts "Stderr:"
puts result.stderr
# Print as it goes:
result = Runner.new('ls -al', print_to: $stdout).run
如果您需要模拟实时标准输入(按键),那么您需要为标准输出数据流创建某种匹配器,并在预期提示通过流时将响应写入命令的标准输入。PTY.spawn
在这种情况下,使用或使用 3rd 方 gem可能会更好。
您还可以将标准输入数据写入临时文件并使用 shell 自己的重定向:
require 'tempfile'
tempfile = Tempfile.new
tempfile.write(stdin_data)
tempfile.close
system(%(do_stuff < "#{tempfile.path}"))
tempfile.unlink