Ruby 可以访问 shell 命令的输出吗?

发布于 2024-08-30 19:35:15 字数 105 浏览 5 评论 0原文

我的 Ruby 脚本正在运行 shell 命令并解析它的输出。但是,似乎该命令首先执行,并将输出保存在数组中。我希望能够在打印输出行时实时访问它们。我已经玩过线程,但还没有让它工作。有什么建议吗?

My Ruby script is running a shell command and parsing the output from it. However, it seems the command is first executed and output saved in an array. I would like to be able to access the output lines in real time just as they are printed. I've played around with threads, but haven't got it to work. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小姐丶请自重 2024-09-06 19:35:15

您正在寻找管道。这是一个例子:

# This example runs the netstat command via a pipe
# and processes the data in Ruby as it come back

pipe = IO.popen("netstat 3")
while (line = pipe.gets)
  print line
  print "and"
end

You are looking for pipes. Here is an example:

# This example runs the netstat command via a pipe
# and processes the data in Ruby as it come back

pipe = IO.popen("netstat 3")
while (line = pipe.gets)
  print line
  print "and"
end
贱贱哒 2024-09-06 19:35:15

当调用方法/函数来运行系统/shell 命令时,您的解释器会生成另一个进程来运行它并等待它完成,然后为您提供输出。

即使您使用线程,您唯一要做的就是在命令运行时不让程序挂起,但在命令完成之前您仍然无法获得输出。

我认为你可以用管道来实现这一点,但我不确定如何实现。

@马塞尔明白了。

When call methods/functions to run system/shell commands, your interpreter spawns another process to run it and waits for it to finish, then gives you the output.

Even if you use threads, the only thing that you would accomplish is not letting your program to hang while the command is run, but you still won't get the output till its done.

I think you can accomplish that with pipes, but I am not sure how.

@Marcel got it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文