user1091949 user1091949 - 25 days ago 7
Ruby Question

How do I pass an angle bracket ("<") to IO.popen in Ruby?

This command works fine when using backticks to make a system call:

aspell -a < /path/textfile


However, if I try this it does not work:

result = IO.popen(["aspell", "-a", "<", "/path/textfile"]).read


It seems to be an issue with the angle bracket, because this works fine:

result = IO.popen([ "aspell", "--help"]).read


What am I doing wrong here?

Answer

That's a shell operation, and as popen is interfacing directly with your command, you can't do it. Instead you assume the responsibility for doing this, which is why the Open3 library exists and things like the popen2 method in particular:

Adapting your code:

require 'open3'

Open3.popen2('aspell', '-a') do |stdin, stdout, wait_thr|
  # Feed the contents of /path/textfile into the STDIN of this
  # subprocess.
  stdin.write(File.read('/path/textfile'))
  stdin.close

  # Read the results back
  result = stdout.read
end

This might be advantageous since you no longer need to write to a temporary file to do operations like this, you can just feed in data directly through the stdin pipe.