【问题标题】:Executing the top command using Open3 in ruby在 ruby​​ 中使用 Open3 执行 top 命令
【发布时间】:2018-01-14 13:25:34
【问题描述】:

我正在尝试使用 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 来执行该命令吗?还有其他执行方式吗?我做错了吗?

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

提前致谢。

【问题讨论】:

    标签: ruby popen3


    【解决方案1】:

    你可以通过打印块参数e看到你的问题:

    错误应该是这样的:

    顶部:tty 获取失败

    这在尝试以非交互模式运行 top 时很常见。要覆盖它,您需要 top-b 选项。

    -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​​ 中系统调用也有很多方法,check them here

    【讨论】:

    • @AnishV 很高兴为您提供帮助。如果这个答案被接受,我将不胜感激。
    • 糟糕。堆栈溢出也是新的。标记。 :)
    猜你喜欢
    • 2022-01-15
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多