Skip to content

Instantly share code, notes, and snippets.

@rabbitt
Created March 8, 2014 05:57
Show Gist options
  • Save rabbitt/9426020 to your computer and use it in GitHub Desktop.
Save rabbitt/9426020 to your computer and use it in GitHub Desktop.
testing command execution ideas
require 'open3'
require 'pp'
require 'eventr'
require 'stringio'
$eventr = Eventr::Coordinator.instance
$eventr.publishers(:stderr, :stdout)
$eventr.consumer(:stderr) { |msg| $stderr.puts "STDERR: #{msg}" }
$eventr.consumer(:stdout) { |msg| $stdout.puts "STDOUT: #{msg}" }
$eventr.start
ENV_WHITELIST = %w( PATH HOME LDFLAGS CPPFLAGS DISPLAY EDITOR LANG LC_ALL SHELL SHLVL TERM TMPDIR USER )
def prep_env(env = nil)
env ||= Hash[ENV]
Hash[env].inject([]) { |array,(k,v)|
array << "#{k}=#{v}" if ENV_WHITELIST.include? k
array
}
end
def command(*args)
env_arr = prep_env(Hash[ENV])
cmd = args.join(' ')
puts "Command: #{cmd}"
result = Open3.popen3('/usr/bin/env', '-i', *env_arr, 'bash', '-c', cmd) do |i, out, err, thr|
o = Thread.new do
output = StringIO.new
loop {
begin
output << _o = out.readpartial(4096)
$eventr.publish(:stdout, _o)
rescue EOFError
break
end
}
output.rewind
output.read
end
e = Thread.new do
error = StringIO.new
loop {
begin
error << _e = err.readpartial(4096)
$eventr.publish(:stderr, _e)
rescue EOFError
break;
end
}
error.rewind
error.read
end
sleep 1 while thr.alive?
[ o.value, e.value, thr.value ]
end
end
pp command('sleep 3; echo foo; sleep 2; echo 2; sleep 1; echo bar')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment