So long as the command sends its output to its STDOUT (e.g. piping to a file is possible), you can collect the result using Ruby's "backtick" or "%x" notation. In this case, the command must execute and exit before you can collect the result, so you have to be careful that the command doesn't take too long, otherwise it might trigger the Ruby time-out.
This would look something like this...
- Code: Select all
# Using backticks to delimit the command string...
result = `command -switch1 -switch2 ... parameter1 parameter2 ...`
# OR, using the %x notation...
result = %x{command -switch1 -switch2 ... parameter1 parameter2 ...}
# Check that the command executed successfully.
if $?.success?
# do something with the result.
end
Note...
- When you use the %x notation, you can use any type of bracket pair, or any other single character, as the delimiter.
-
$? is a global variable which will contain a
Process::Status object for the most recent command, from which you can determine whether the command executed successfully, its exit code, etc.
- You can insert variable values into the command string by using Ruby's usual
#{...} string interpolation. e.g...
- Code: Select all
result = `command #{@my_variable}`
If the command is something which needs to stay running rather than a "single-shot" command, then things get more complex, as there's not a simple way that I know of to synchronise collecting the output with the event-driven system of FlowStone Ruby. Using a pipe to a file, and then polling the file from FS, is probably going to be the easiest way. In this case, you need to launch the command differently so that Ruby doesn't wait for the command to exit...
- Code: Select all
# Launch the command and read its process ID...
pid = spawn("command -switch1 -switch2 ... parameter1 parameter2 ... >> file.txt")
# Set the command free to run independently
# (NB: Capital 'P' for 'Process' - it's a module, not a method.)
Process.detach(pid)
If you have plenty of memory, the file stays small, and you delete it when you're done, it will likely remain in virtual page file memory rather than being written to disk - so using a file in this way isn't always as inefficient as it might appear.