从Ruby执行命令并检索STDOUT和STDERR

时间:2019-03-11 03:01:15

标签: ruby

我有一个执行系统命令的Ruby可执行文件。我需要以下行为:

  1. 子命令中的STDOUT和STDERR应该实时显示(就像我直接从命令行执行子命令一样)。
  2. 就在我的可执行文件结束之前,我想检索添加到STDOUT和STDERR中的所有内容,以便我可以对其进行检查。

使这项工作最好的方法是什么?我过去曾使用capture3执行命令并获得STDOUT / STDERR,但是capture3却禁止了终端的输出。我以前使用过反引号和system,但它们只让我轻松访问STDOUT。

1 个答案:

答案 0 :(得分:1)

您可以观看 PauseTransition pause = new PauseTransition(Duration.seconds(5)); pause.setOnFinished(event ->{ if (! primaryStage.isIconified()) { primaryStage.setIconified(true); } else { primaryStage.setIconified(false); } pause.play(); }); pause.play(); 返回的stdout和stderr句柄,并在收集时重新打印它们。

为方便起见,这里有一个完整的Open3.popen3课程,我在这里学习:

Runner

您可以这样做:

require 'open3'

class Runner
  attr_reader :cmd, :exit_status, :stdout, :stderr

  # Run a command, return runner instance
  # @param cmd [String,Array<String>] command to execute
  def self.run(*cmd)
    Runner.new(*cmd).run
  end

  # Run a command, raise Runner::Error if it fails
  # @param cmd [String,Array<String>] command to execute
  # @raise [Runner::Error]
  def self.run!(*cmd)
    Runner.new(*cmd).run!
  end

  # Run a command, return true if it succeeds, false if not
  # @param cmd [String,Array<String>] command to execute
  # @return [Boolean]
  def self.run?(*cmd)
    Runner.new(*cmd).run?
  end

  Error = Class.new(StandardError)

  # @param cmd [String,Array<String>] command to execute
  def initialize(cmd)
    @cmd = cmd.is_a?(Array) ? cmd.join(' ') : cmd
    @stdout = +''
    @stderr = +''
    @exit_status = nil
  end

  # @return [Boolean] success or failure?
  def success?
    exit_status.zero?
  end

  # Run the command, return self
  # @return [Runner]
  def run
    Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
      until [stdout, stderr].all?(&:eof?)
        readable = IO.select([stdout, stderr])
        next unless readable&.first

        readable.first.each do |stream|
          data = +''
          # rubocop:disable Lint/HandleExceptions
          begin
            stream.read_nonblock(1024, data)
          rescue EOFError
            # ignore, it's expected for read_nonblock to raise EOFError
            # when all is read
          end

          if stream == stdout
            @stdout << data
            $stdout.write(data)
          else
            @stderr << data
            $stderr.write(data)
          end
        end
      end
      @exit_status = wait_thr.value.exitstatus
    end

    self
  end

  # Run the command and return stdout, raise if fails
  # @return stdout [String]
  # @raise [Runner::Error]
  def run!
    return run.stdout if run.success?

    raise(Error, "command failed, exit: %d - stdout: %s / stderr: %s" % [exit_status, stdout, stderr])
  end

  # Run the command and return true if success, false if failure
  # @return success [Boolean]
  def run?
    run.success?
  end
end