Running external commands in Ruby

Posted by Adrian O'Connor Wed, 18 Apr 2007 20:12:00 GMT

Ruby is great for automating many tasks, and often this requires starting other programmes and collecting their output.

This is a very short article that demonstrates one way of doing this. We shall demonstrate calling the ‘dir’ command and storing the output. It’s a bit basic, but it illustrates the point.

example.rb:

p = IO.popen("dir C:\\")
puts p.readlines

You’ll notice that we’ve collected the output as a string, which we then display. In the real world you could, of course, parse the output and take further action or simply log it in a database.

This also works in Rails and allows us to build useful control panel applications. If you are running your application as a Windows service (either through Apache or Mongrel Service) you need to be aware that the account your service runs as will affect the permissions and privileges available to the commands.

I have used this technique to successfully run various commands in an automated environment, including the subversion commands which, rather cleverly, have an xml switch so that they produce their output in an easily parse-able format.

Comments

Leave a response

Comments