2010-09-06 116 views
2

我寫了這一點,但它didn`t工作...如何使用Ruby和IO.popen編寫和讀取進程?

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

我重寫這樣

 
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 expect exit from irb 
end 
但它didn`t工作太

回答

3

要麼

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

或做

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 
+0

我重寫這樣

IO.popen("irb", "r+") do |pipe| 3.times {puts pipe.gets} # startup noise pipe.puts "10**6\n" puts pipe.gets # I expect " => 1000000" pipe.puts "quit" # I expect exit from irb end
但它didn't工作太 – mystdeim 2010-09-06 16:32:40

+0

與'2.times',而不是'3.times'嘗試。我在'.irbrc'中有'puts'。 – Reactormonk 2010-09-06 16:39:47

+0

沒有:(我不能退出irb ... – mystdeim 2010-09-06 16:51:21

2

通常,ab這個例子會掛起,因爲管道仍然是寫着,你調用的命令(Ruby解釋器)期望進一步的命令/數據。

另一個答案發送__END__紅寶石 - 這在這裏工作,但這個技巧當然不會與任何其他程序,您可以通過popen調用。

當您使用popen時,您需要關閉管道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 

參見:

Ruby 1.8.7 IO#close_write

Ruby 1.9.2 IO#close_write

相關問題