Ruby 可以访问 shell 命令的输出吗?
我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找管道。这是一个例子:
You are looking for pipes. Here is an example:
当调用方法/函数来运行系统/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.