Basic Ruby: Running external commands

Posted by Adrian Fri, 26 Jun 2009 21:03:00 GMT

This brief article explains how you can call executables and scripts from your Ruby program.

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.


About

We are a small British company that produces business-oriented software and solutions. These articles are a product of our daily work - information that we think might be useful to share. We hope you find them useful.

Our Software

These are some of our products. Several are open source, some are web-based and others are proprietary:

Categories

Archives

Syndicate

ml> ._trackPageview(); } catch(err) {} ml> l> pageTracker._trackPageview(); } catch(err) {} ml> ._trackPageview(); } catch(err) {} ml> l>