使用popen3实现rake任务的实时输出

问题描述 投票:1回答:1

在获得实时输出时,似乎无法在popen3块中运行rake任务。在rake任务结束时,所有行都会立即出现。我试图通过popen3块从rake任务获得实时输出

cmd = 'rake perform_a_task'
Open3::popen3(cmd) do |std_in, std_out, std_err|
  std_out.each_line do |line|
    puts line
  end
end

How to reproduce

Proof of concept: the rake task

  1. 创建如下任务
task :print_and_wait do
  puts 'A'
  sleep 1
  puts 'B'
  sleep 1
  putc 'C'
end
  1. 从命令行调用该任务

$ rake print_and_wait输出3行(A,B和C),其间有一秒钟的暂停。正如所料

Proof of concept 2: popen3

  1. 创建一个shell脚本
$ cat print_and_wait
#!/bin/bash
echo 'A'
sleep 1
echo 'B'
sleep 1
echo 'C'
  1. 创建一个ruby脚本
$ cat print_and_wait.rb
require 'open3'

def exec_async(cmd)
  Open3::popen3(cmd) do |std_in, std_out, std_err|
    std_out.each_line do |line|
      puts line
    end
  end
end

exec_async './print_and_wait'
  1. 运行ruby脚本

$ ruby print_and_wait.rb按预期工作:输出3行,中间暂停一秒

Where it does not work

  • 编辑ruby脚本print_and_wait.rb并将exec_async './print_and_wait'更改为exec_async 'rake print_and_wait'
  • 运行$ ruby print_and_wait.rb
  • 没有输出,3秒后所有3行同时打印

我尝试了几种组合,但从未能按预期工作。知道为什么这不起作用?这是一个错误吗?

谢谢

ruby rake rake-task popen3
1个回答
1
投票

在rake任务开始时添加$stdout.sync = true解决了它。

© www.soinside.com 2019 - 2024. All rights reserved.