A Simple and Portable Ruby Interface to InChI Part 2 - Silencing Console Output

The previous article in this series described a simple and portable method for interfacing Ruby to the cInChI-1 binary. One disadvantage was noisy console output. This article offers a minor modification to disable it.

The Code

module InChI
  def inchi_for molfile
    output = %x[echo "#{molfile}" | cInChI-1 -STDIO 2>/dev/null]

    output.eql?("") ? "" : output.split(/\n/)[1]
  end
end

Here, we're taking advantage of the ability to redirect certain output streams to /dev/null.

Testing the Code

Saving the above in a file called inchi.rb, we can test it from IRB. To make things interesting, let's pull a molfile from Chempedia:

irb
irb(main):001:0> require 'open-uri'
=> true
irb(main):002:0> require 'inchi'
=> true
irb(main):003:0> include InChI
=> Object
irb(main):004:0> open 'http://chempedia.com/compounds/83490.mol' do |f|
irb(main):005:1*   puts inchi_for(f.read)
irb(main):006:1> end
InChI=1/C15H15NO3S/c17-14(16-18)11-20(19)15(12-7-3-1-4-8-12)13-9-5-2-6-10-13/h1-10,15,18H,11H2,(H,16,17)
=> nil

We should be able to run this code unmodified on any UNIX-like system in which the cInChI-1 binary is on the path. And of course we could take this one step further by allowing command line options to be passed in as parameters to the inchi_for method.

Simplicity has its advantages.