0

I am trying to execute the "top -n 1" command in ruby using the Open3 module in ruby.

This is my code

command = "top -n 1"
Open3.popen3 (command) do |i,o,e,t|
        i.close
        exit_status = t.value
        unless exit_status.success?
                puts "NOPE"
        end
        t.value
end

All I get is NOPE. Even if I try to print o.read or o.gets all I get is a blank line.

Is there anyway I can use open3 to execute that command? Are there any other ways of executing it ? Am I doing something wrong?

I see that I can use the backticks(`) to execute system command. Is that a good practice? I saw several articles and blogs saying it isn't.

Thanks in advance.

Anish V
  • 130
  • 1
  • 8

1 Answers1

1

You can see your problem by printing block parameter e:

The error should be like this:

top: failed tty get

This is common when trying to run top in non-interactive mode. To override this, you need the -b option of top.

-b  :Batch-mode operation
    Starts top in Batch mode, which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept  input  and
    runs until the iterations limit you've set with the `-n' command-line option or until killed.

command = 'top -bn 1' is ok then.

Also there are many ways for system calling in ruby, check them here.

halfelf
  • 9,737
  • 13
  • 54
  • 63