0

我正在尝试使用 ruby​​ 中的 Open3 模块在 ruby​​ 中执行“top -n 1”命令。

这是我的代码

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

我得到的只是NOPE。即使我尝试打印o.read或者o.gets我得到的只是一个空行。

无论如何我可以使用 open3 来执行该命令吗?还有其他执行方式吗?难道我做错了什么?

我看到我可以使用反引号(`)来执行系统命令。这是一个好习惯吗?我看到几篇文章和博客说不是。

提前致谢。

4

1 回答 1

1

您可以通过打印块参数来查看您的问题e

错误应该是这样的:

顶部: tty 获取失败

这在尝试以top非交互模式运行时很常见。要覆盖它,您-b需要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'那么就可以了。

ruby 中的系统调用也有很多方法,请在此处查看

于 2017-08-07T09:49:54.233 回答