Input setup for system () calls in ruby

I am trying to upload a file using net / sftp and pass its contents as stdin for a command line application. I can do this by first writing the file to disk, but I would prefer to avoid this step.

Is there a way to control the entrance to a program called using system() in ruby?

+4
source share
3 answers

Do not use system at all for this kind of thing, system best for running the external command you put on I need to talk.

Use Open3.open3 or Open3.open2 to open several pipes for an external process, and then write to the stdin pipe in the same way as writing to any other I / O channel; if there is any output for processing, then you can read it directly from the stdout pipe in the same way as reading from any other input / output input channel.

+10
source

Is something like this possible (using open, as mu suggested)?

 contents = "Hello, World!" open('|echo', 'w') { puts contents } 
+2
source

This can also be done using IO.expect

 require 'pty' require 'expect' str = "RUBY_VERSION" PTY.spawn("irb") do |reader, writer| reader.expect(/0> /) writer.puts(str) reader.expect(/=> /) answer = reader.gets puts "Ruby version from irb: #{answer}" end 

It is expected that the spawned process will display "0>" (the end of the irb prompt) and when it sees that it is printing a specific line. He then searches for the IRB, waiting for it to display "=>" and capture the returned data.

+2
source

All Articles