Search code examples
rubysidekiq

Output STDOUT to a file with ruby during execution


What is the best way to output the STDOUT to a file while a process is running? I made a test script called "runMyScript" and it has some echo statements with some sleeps in between.

I am using Rails and Sidekiq to run this worker:

class RunBuildWorker

  include Sidekiq::Worker

  sidekiq_options retry: false, backtrace: true

  def perform(file_name)
    IO.popen('runMyScript blah blah blah blah') do |io|
      File.open(FILE_MANAGER.configuration_directory + file_name, 'a') do |file|
        while (line = io.gets)
            file.write line
        end
      end
    end
  end

end

Unfortunately, it isn't writing to the file until the process is complete. How would I go about writing to the file during execution?

Update:

Here is what the script is currently.

COUNTER=0
while [ $COUNTER -le 5 ]                                                                                                                                    
do
    echo "The counter is $COUNTER"
    sleep 1
    COUNTER=$(( $COUNTER + 1 ))
done

I should mention this is just a test script so I can try to redirect output, there is another script that was written by another team that I'll actually be using in the future.


Solution

  • What about

    system("runMyScript blah blah blah blah > #{FILE_MANAGER.configuration_directory + file_name}")
    

    This redirects any output printed to stdout to your file (redirect is done on console-level). If you want to append to the file, simply replace > with >>.