Passing a string as stdin to a popen


#1

Say I have some content in a ruby string and I want to pass it as
stdin input to a command. I then want to read the output.

I tried this:

IO.popen(“mycommand”, mode=‘r+’) do |io|
io.write mytext
result = io.read
end

This resulted in a “Broken Pipe” exception. What’s the correct way to do
this?

Thanks,

Pedro.


#2

On 5/31/06, Logan C. removed_email_address@domain.invalid wrote:

I’m not sure exactly what the problem is, but I imagine that
io.write mytext
io.close_write # let the process know you’ve given it all the data
result = io.read

will fix things right up.

Yes, this works. The problem with this is that since I only read after
I write the whole thing the process might block since noone is reading
from it and not write anything. Is there some way I can connect the io
object I get from popen to another io object I create myself. So as to
create an actual pipe in ruby?

Pedro.


#3

On May 31, 2006, at 11:30 AM, Pedro Côrte-Real wrote:

This resulted in a “Broken Pipe” exception. What’s the correct way
to do this?

Thanks,

Pedro.

I’m not sure exactly what the problem is, but I imagine that
io.write mytext
io.close_write # let the process know you’ve given it all the data
result = io.read

will fix things right up.


#4

2006/6/1, Pedro Côrte-Real removed_email_address@domain.invalid:

from it and not write anything. Is there some way I can connect the io
object I get from popen to another io object I create myself. So as to
create an actual pipe in ruby?

I suspect the error was caused because the process had terminated
already:

IO.popen(“ls”, “r+”) {|io| sleep 5; io.write “test”}
Errno::EPIPE: Broken pipe
from (irb):1:in `write’
from (irb):1
from (irb):1
from :0

Does the process you start maybe not read its stdio? Or stop reading
after some time has passed without input? Where exactly do you get
the exception? Is it during read or write?

If you need to read and write interleavingly then I suggest you use a
second thread.

Regards

robert


#5

On 6/1/06, Robert K. removed_email_address@domain.invalid wrote:

after some time has passed without input? Where exactly do you get
the exception? Is it during read or write?

Yes, that was it. I was passing some wrong options to the program and
it was exiting without reading it’s input. It’s solved now. What I’m
doing is running “xsltproc” to convert some XML into HTML with a XSLT.
I guess a better idea would be to do it directly in ruby but ubuntu’s
libxslt-ruby1.8 seems to be broken.

Pedro.