我有以下Ruby块:
ruby_block "Validate" do
block do
require "mixlib/shellout"
begin
cmd = Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)
cmd.live_stream = STDOUT
cmd.run_command
cmd.error!
rescue Exception => e
puts "Action failed..."
return 168
end
end
action :create
notifies :create, "ruby_block[Validated]", :immediately
not_if { node[:state][:validated] == true }
end我想将脚本的结果记录到STDOUT和一个名为“/tmp/xml_diff_Resul.txt”的文件中。
我做的第一件事就是改变:
cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)至:
cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py > /tmp/xml_diff_results.txt", :timeout => 3600)然而,这并没有达到我的预期。
然后我注意到了cmd.live_stream变量。有什么办法可以让我利用它来做这样的事吗?
cmd.live_stream = (STDOUT > /tmp/xml_diff_results.txt)解决方案:
解决我的问题的方法很简单,并且受到了“厨具”的启发。
log_file = File.open('/tmp/chef-run.log', File::WRONLY | File::APPEND)
LOG = Logger.new(log_file)
def shell(command)
LOG.info "Execute: #{command}"
cmd = Mixlib::ShellOut.new(command, :timeout => 1800)
cmd.run_command
LOG.info "Returned: #{cmd.stdout}"
cmd.error!
cmd
end发布于 2016-11-02 09:35:46
Ruby中的另一个选项(只是内部部分),以防tee不可用(windows):
cmd = Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)
cmd.live_stream = STDOUT
cmd.run_command
# new part
log=::Tempfile.new(["xml_diff_results",".txt"])
errlog=::File.open(log.path.gsub(".txt",".err")
log.write(cmd.stdout)
errlog.write(cmd.stderr)
log.close
errlog.close
Chef::Log.info("Log results are in #{log.path}")
# end of new part
cmd.error!如果您运行的是没有Chef::Log的主厨客户端,并且真正希望在主厨日志中打印路径,则将-l info级别更改为warn。
主要的优点是它的平台无关,缺点是日志文件只有在命令结束执行后才会被写入。
发布于 2016-11-01 00:44:50
这不是红宝石,甚至不是厨师的问题。这更像是一个沉重的问题
运行命令并将其输出重定向到stdout和文件的一种方法是使用tee。
echo 'Hello World!' | tee output.log所以,用你的例子可以是这样的
cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py | tee /tmp/xml_diff_results.txt", :timeout => 3600)https://stackoverflow.com/questions/40352299
复制相似问题