Saturday, August 21, 2010

Executing a command line program from within Ruby

This is a ruby program to execute a command-line program.
This is based on suggestion by geraldm in http://ubuntuforums.org/archive/index.php/t-544457.html.

# execprog.rb

class StdClass
  def initialize  
  end 

  def test
    bb = IO.popen("ls -la")
    b = bb.readlines
    puts b.join
    bb.close
  end 
end

x = StdClass.new
x.test

And here is the result:

$ ruby execprog.rb
total 16
drwx------ 2 4096 2010-08-21 13:54 .
drwxr-xr-x 5 4096 2010-08-21 08:55 ..
-rw-r--r-- 1 1034 2010-08-21 13:54 execprog.rb
-rw-r--r-- 1 1010 2010-08-21 08:43 helloworld.rb
$

2 comments:

  1. hi,
    there is an error in your program: you have forgotten to close the pipe. bb.close.

    And besides, you can rewrite this program even better:
    def test
    IO.popen("ls -la").each {|line| puts line}
    end

    Using block in popen will close the pipe automatically once there is no input.

    ReplyDelete