开发者

How to write and read from process with Ruby and IO.popen?

开发者 https://www.devze.com 2023-01-14 20:15 出处:网络
I wrote this, but it didn`t work... output = IO.popen(\"irb\", \"r+\") do |pipe| pipe.gets pipe.puts \"10**6\"

I wrote this, but it didn`t work...

output = IO.popen("irb", "r+") do |pipe|
  pipe.gets
  pipe.puts "10**6"
  pipe.gets
  pipe.puts "quit"
end

I rewrite so

IO.popen("irb", "w+") do |pipe|
  3.times {puts pipe.gets} # startup noise
  pipe.puts "10**6\n"
  puts pipe.gets # I expect " => 1000000"
  pipe.puts "quit" # I exp开发者_如何学Pythonect exit from irb
end 
but It didn`t work too


Either do

IO.popen("ruby", "r+") do |pipe|
  pipe.puts "puts 10**6"
  pipe.puts "__END__"
  pipe.gets
end

or do

IO.popen("irb", "r+") do |pipe|
  pipe.puts "\n"
  3.times {pipe.gets} # startup noise
  pipe.puts "puts 10**6\n"
  pipe.gets # prompt
  pipe.gets
end


In general the above example will hang because the pipe is still open for writing, and the command you called (the ruby interpreter) expects further commands / data.

The other answer sends __END__ to ruby -- this works here, but this trick will of course not work with any other programs you might call via popen.

When you use popen you need to close the pipe with IO#close_write.

 IO.popen("ruby", "r+") do |pipe|
   pipe.puts "puts 10**6"

   pipe.close_write    # make sure to close stdin for the program you call

   pipe.gets
 end

See also:

Ruby 1.8.7 IO#close_write

Ruby 1.9.2 IO#close_write

0

精彩评论

暂无评论...
验证码 换一张
取 消