开发者

Problem with using open4 in Ruby

I have a script I want to execute with open4.

Here is the file:

script

#!/usr/bin/env ruby
print "Enter your username: "
username = gets
puts "Here is your username: #{username}"
print "Enter your password: "
password = gets
puts "Here is your password: #{password}"

Then I fire up IRB and type:

ruby-1.9.2-p0 > pid, stdin, stdout, stderr = Open4::popen4("./script")
=> [2649, #<IO:fd 9>, #<IO:fd 11>, #<IO:fd 开发者_Go百科13>]

ruby-1.9.2-p0 > puts stdout.gets

In the last line I thought it should give me "Enter your username: " but it didn't. The screen is empty no matter what I type. I can only terminate it with CTRL+C.

Then i run...

ruby-1.9.2-p0 > puts stdout.gets

...again, and this time it gives me "Enter your username: ".

Does someone know why?


It is because stdout.gets wants to read an entire line including \n but the script hasn't printed a newline so far.

So one thing you need to do is replace print with puts.

Another thing is that the child's output is buffered. You need to set $stdout.sync = true at its start or call $stdout.flush after each puts.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜