如何在 ruby 中获得 wget 输出?

How do I get wget output in ruby?

我需要 运行 来自 ruby 的以下代码:

system "wget http://example.org/some/large/archive.zip"

当我 运行 我看到这个命令时

Redirecting output to ‘wget-log’.

我需要做 tail -f wget-log 才能看到进度

如何在 运行 ruby 进程所在的终端中查看 wget 输出?

我试过了

system "wget -O - http://example.org/some/large/archive.zip > dev/null"

但没用

也许还有其他选项可以使用 ruby 下载大型档案并查看进度?

您可以使用 Open3 模块,它位于 Ruby 的标准库中。

授予您访问 stdout、stderr、退出代码和一个线程以在 运行 另一个程序 时等待子进程。

因此,使用 pwd 命令,您可以执行以下操作:

require 'open3'
stdout, stderr, status = Open3.capture3('pwd')
puts stdout # ~/ current directory
puts stderr #    no error
puts status # pid 25522 exit 0

ruby 提供了一个很好的内置库来制作任何类型的 http 东西,例如下载文件你可以使用 net/http:

require 'net/http'
require 'uri'

uri = URI(URI.encode("http://example.org/some/large/archive.zip"))
Net::HTTP.start(uri.host,uri.port) do |http|
  request = Net::HTTP::Get.new uri.path

  http.request request do |response|
    open "/tmp/my_large_file.zip", 'w' do |io|
       response.read_body do |chunk|
         puts "Writing  #{chunk.length} bits ..." # see progress
         io.write chunk
       end
     end
  end  
end

使用 wget 您无法 捕获您的 ruby 代码中的任何类型的 http 错误。*

使用 wget 您无法 进行身份验证,例如在您的 ruby 代码中进行基本验证。*

使用Ruby内置库,非常强大。

你可以,但有一些错误代码