在Ruby中与子进程通信 [英] Communicate with subprocess in Ruby

查看:159
本文介绍了在Ruby中与子进程通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何在Ruby中启动子进程并使用已启动子进程的stdin和stdout与它进行通信?如下所示:

Does anybody know how to start a subprocess in Ruby and communicate with it using the stdin and stdout of the started subprocess? Something like the following:

IO.popen("subprocess", "r+") do |io|
  io.puts(question1)
  answer1 = io.gets
  question2 = follow_up_question(question1, answer1)
  io.puts(question2)
  answer2 = io.gets
  # etc
end

关键是我想做互动。我不想只是为已启动的程序发送所有输入,然后检索所有输出,但我想发送内容并随后收到答案。有什么办法吗?我尝试了IO.popen,Open3.popen2和大约10个其他方法,但是所有这些方法都希望你先发送子进程的所有输入然后检索所有输出。我找不到任何交互方法。

The key point is that I want to do interaction. I don't want to just send all the input for the started program and then retrieve all the output, but I want to send stuff and receive answers subsequently. Is there any way to do it? I tried IO.popen, Open3.popen2 and about 10 other methods, but all of them expect that you send all the input for the subprocess first and then retrieve all the output. I found no method for interaction.

推荐答案

你写的代码对我有用 cat program:

The code you wrote works for me with the cat program:

IO.popen("cat", "r+") do |io|
  io.puts("abcdef\n")
  answer1 = io.gets
  puts answer1
  io.puts("#{answer1.chomp}ghijkl\n")
  answer2 = io.gets
  puts answer2
end

这打印

abcdef
abcdefghijkl

也许您需要在置入之后刷新 io

Maybe you need to flush your io after puts?

这篇关于在Ruby中与子进程通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆