Class: Boxes::Subprocess

Inherits:
Object
  • Object
show all
Defined in:
lib/boxes/subprocess.rb

Overview

Standardise handling the stdout and stderr from Open3.

Examples:

Print the values returned to stdout and stderr

Boxes::Utils::Subprocess.run 'ls' do |stdout, stderr, thread|
  puts stdout unless stdout == nil
  puts stderr unless stderr == nil
end

Class Method Summary collapse

Class Method Details

.run(command) {|stdout, stderr, thread| ... } ⇒ Object

Create a new subprocess with a command, with a block for the response.

Parameters:

  • cmd (String)

    the command to run

Yields:

  • (stdout, stderr, thread)

    Gives the stdout, stderr and process thread to the block.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/boxes/subprocess.rb', line 16

def self.run(command) # rubocop:disable Metrics/MethodLength
  # see: http://stackoverflow.com/a/1162850/83386
  Open3.popen3(command) do |_stdin, stdout, stderr, thread|
    # read each stream from a new thread
    { out: stdout, err: stderr }.each do |key, stream|
      stream.each_line do |line|
        if key == :out
          yield line, nil, thread if block_given?
        elsif key == :err
          yield nil, line, thread if block_given?
        end
      end
    end

    thread.join # don't exit until the external process is done

    thread.value
  end
end