Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何将脚本输出记录到标准输出和文件_Ruby_Mixlib Shellout - Fatal编程技术网

Ruby 如何将脚本输出记录到标准输出和文件

Ruby 如何将脚本输出记录到标准输出和文件,ruby,mixlib-shellout,Ruby,Mixlib Shellout,我有以下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! res

我有以下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\u diff\u results.txt”的文件中

我做的第一件事就是改变:

cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)
致:

然而,这并没有达到我的预期

然后我注意到
cmd.live\u stream
变量。有没有一种方法可以让我利用它做类似的事情

cmd.live_stream = (STDOUT > /tmp/xml_diff_results.txt)
解决方案:

我的问题的解决方案很简单,灵感来自@tensibai

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

这不是红宝石问题,甚至不是厨师问题。这更像是一个狂欢节的问题

运行命令并将其输出重定向到stdout和文件的一种方法是使用

echo 'Hello World!' | tee output.log
所以,以你的例子来说,可能是这样的

cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py | tee /tmp/xml_diff_results.txt", :timeout => 3600)
如果
tee
不可用(windows),Ruby中的另一个选项(仅内部部分):

如果运行Chef客户端时没有
-l info
,并且确实希望在Chef日志中打印路径,请将
Chef::Log
级别更改为
warn


主要优点是它与平台无关,缺点是只有在命令结束执行后才会写入日志文件。

这与python有什么关系?这可能会起作用。明天当我的分支合并后,我会试一试。实际上,这更像是我正在寻找的。我现在要测试它。@Jakir00我忘了说它是未测试的代码,如果您能确认这是正确的(据我所知,它应该是shell_out,但我可能错过了一个案例),我会很高兴使用它作为psudo代码工作。我没有复制/粘贴它,但我最终使用这种方法从命令输出中写入日志。谢谢
cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py | tee /tmp/xml_diff_results.txt", :timeout => 3600)
  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!