Skip to content

Instantly share code, notes, and snippets.

@benben
Created May 23, 2012 10:50
Show Gist options
  • Save benben/2774544 to your computer and use it in GitHub Desktop.
Save benben/2774544 to your computer and use it in GitHub Desktop.
run shell commands and redirect output to stdout/stderr and seperate files stdout.log and stderr.log
require 'open3'
class MultiIO #stolen from here: http://stackoverflow.com/a/6407200/828277
def initialize(*targets)
@targets = targets
end
def write(*args)
@targets.each {|t| t.write(*args)}
end
def close
@targets.each(&:close)
end
def flush(*args)
@targets.each(&:flush)
end
end
$stdout = MultiIO.new(STDOUT, File.open("stdout.log", "w"))
$stderr = MultiIO.new(STDERR, File.open("stderr.log", "w"))
def c command
stdin, stdout, stderr, wait_thr = Open3.popen3(command)
while (line = stdout.gets)
$stdout.write line
end
while (line = stderr.gets)
$stderr.write line
end
end
c "ls -la"
c "ls -la notthere/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment