在 ruby 中使用 Open3 执行 top 命令



我正在尝试使用 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

我得到的只是没有。即使我尝试打印o.reado.gets我得到的只是一个空白行。

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

我看到我可以使用反引号('(来执行系统命令。这是一种好的做法吗?我看到几篇文章和博客说不是。

提前谢谢。

您可以通过打印块参数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 中调用系统也有很多方法,请在此处查看。

最新更新