Tony Han
Tony Han

Reputation: 2230

Can I display the log of system call in Ruby?

I need to call a command(in a sinatra or rails app) like this:

`command sub`

Some log will be outputed when the command is executing. I want to see the log displaying continuously in the process.

But I just can get the log string after it's done with:

result = `command sub`

So, is there a way to implement this?

Upvotes: 2

Views: 759

Answers (2)

peter
peter

Reputation: 42207

On windows i have the best experience with IO.popen

Here is a sample

require 'logger'

$log = Logger.new( "#{__FILE__}.log", 'monthly' )
#here comes the full command line, here it is a java program
command = %Q{java -jar getscreen.jar #{$userid} #{$password}}
$log.debug command
STDOUT.sync = true
begin
  # Note the somewhat strange 2> syntax. This denotes the file descriptor to pipe to a file. By convention, 0 is stdin, 1 is stdout, 2 is stderr.
  IO.popen(command+" 2>&1") do |pipe|
    pipe.sync = true
    while str = pipe.gets #for every line the external program returns
      #do somerthing with the capturted line
    end
  end
rescue => e
  $log.error "#{__LINE__}:#{e}"
  $log.error e.backtrace
end

Upvotes: 2

SamLosAngeles
SamLosAngeles

Reputation: 2968

There's six ways to do it, but the way you're using isn't the correct one because it waits for the process the return.

Pick one from here:

http://tech.natemurray.com/2007/03/ruby-shell-commands.html

I would use IO#popen3 if I was you.

Upvotes: 0

Related Questions