Saturday, January 1, 2022

HOWTO: Use Ruby IO with shell execution (STDIN, STDOUT, STDERR, PID)


# 1. IO.popen
# Runs the specified command as a subprocess; the subprocess's standard
# input and output will be connected to the returned IO object. This
# allows you to provide STDIN input and get STDOUT output easily.
# Asynchronous (IO objects)
# Return: IO object, (IO#pid, IO#read)
# Docs: https://www.rubydoc.info/stdlib/core/IO.popen

io = IO.popen("echo 'hi'") # Or IO.popen(["echo", "hi"])
io = IO.popen(cmd)

IO.popen(["echo", "'hi'"]) do |io|
# ...
end


# 2. open3
# Runs the specified command as a subprocess; the subprocess's standard
# input, stdout, and stderr IO objects are available. There is also
# an "open4" gem to more easily get the PID of the child process.
# Synchronous (get strings) or Asynchronous (IO objects)
# Return: Strings (capture*) or IO objects (popen*)
# Docs: https://docs.ruby-lang.org/en/2.5.0/Open3.html#method-c-popen3

require 'open3'
stdin_io, stdout_io, stderr_io, process_waiter = Open3::popen3(cmd)
stdout_str, stderr_str, process_info = Open3::capture3(cmd)

require 'open4'
pid, stdin, stdout, stderr = Open4::popen4(cmd);


# Extra Advice - Exit Code
# $? which is the same as $CHILD_STATUS (if you require 'english')
# Accesses the status of the last system executed command if
# you use the backticks, system() or %x{}.
# You can then access the ``exitstatus'' and ``pid'' properties
# Docs: https://ruby-doc.org/core-2.7.1/Process/Status.html#method-i-exitstatus

$?.exitstatus

No comments:

Post a Comment