我正在使用IO.popen
来启动一个子IO.popen
,但是我只能得到在子IO.popen
时子IO.popen
运行所花费的时间(有时候是5分钟或其他)的结果。 我真的需要能够看到subprocess写入stderr
和stdout
所有内容。
到目前为止,我找不到任何这样的作品,但我相信这是可能的。
如果你需要得到实时输出,我会建议使用stdlib PTY
而不是popen
像这样的东西:
require 'pty' cmd = 'echo a; sleep 1; cat /some/file; sleep 1; echo b' PTY.spawn cmd do |r, w, pid| begin r.sync r.each_line { |l| puts "#{Time.now.strftime('%M:%S')} - #{l.strip}" } rescue Errno::EIO => e # simply ignoring this ensure ::Process.wait pid end end exit "#{cmd} failed" unless $? && $?.exitstatus == 0 > 33:36 - a > 33:37 - cat: /some/file: No such file or directory > 33:38 - b
这样你就可以立即得到输出,就像在终端一样
您可能想要使用标准库中的Open3.popen3 ,它可以访问作为流的stdin,stdout和stderr。