I know how to run an external process as there are many ways to do so. But how do I capture its output and exit code to the variables? These, the most popular ways of running a process, don't work as I want:
a = `ls -l` # "a" captures only output
b = system "ls -l " # "b" captures only exit code
Here is a way to get this out.
#!/usr/bin/env ruby
require 'open3'
Open3.popen3("ls -l") do |stdin, stdout, stderr, wait_thr|
puts stdout.read
puts wait_thr.value.exitstatus
end
# >> total 52
# >> -rw-r--r-- 1 arup users 0 Aug 5 09:32 a.rb
# >> drwxr-xr-x 2 arup users 4096 Jul 20 20:37 FSS
# >> drwxr-xr-x 2 arup users 4096 Jul 20 20:37 fss_dir
# >> -rw-r--r-- 1 arup users 42 Jul 19 01:36 out.txt
# .....
#...
# >> 0
Doco is very clear of ::popen3
. stdout
gives IO
object. So, we need to use IO#read
method. And wait_thr.value
gives us Process::Status
. Now once we have that object, we can use #exitstatus
method for the same.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments