gpt4 book ai didi

ruby - 如何逐行读取 Ruby 1.8.7 中的 gzip 文件?

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:12 26 4
gpt4 key购买 nike

当我尝试将 gzip 文件逐行读入 Ruby 1.8.7 时,它只读取 gzip 文件的第一行。这不会发生在我的测试机器上,只会发生在我的生产服务器上。

它可能与 zlib 或 Gzipreader 有关,但我目前不知道下一步该做什么,任何建议都会很棒。

require 'zlib'
require 'open-uri'

list = Array.new
file = Dir.glob("*").max_by {|f| File.mtime(f)}


File.open(file) do |f|
gz = Zlib::GzipReader.new(f)
#something right here is causing an issue on production system
list = gz.read
gz.close
end

#I need to take the array and push it to redis
list = list.split("\n")
list.shift
list.each do |list|
puts list
puts "\n\n"
end

最佳答案

首先,您可能希望使用 '*.gz' 而不是 '*',以防脚本的工作目录中还有其他文件。

这里有几个解决方案:

使用 GzipReader(推荐)

require 'zlib'

file = Dir.glob('*').max_by { |f| File.mtime(f) }
fd = File.open(file)
gz = Zlib::GzipReader(fd)

gz.readlines[1..-1].each do |line|
line.chomp!
puts line, "\n\n"
end

使用 IO#popen 和 zcat

您不应将未经过滤的用户输入传递给Kernel#exec 或类似函数,因为它可用于执行任意命令。

在您的情况下,您不是在处理用户输入。因此,需要对脚本的工作目录进行写访问才能执行此操作。然而,这仍然是一种不好的做法——包含特殊 shell 字符('""$" 等)的文件名可能会导致意外问题.

下面的解决方案应该和 GzipReader 一样安全,但通常最好使用标准库而不是依赖外部程序。

file = Dir.glob('*').max_by { |f| File.mtime(f) }

IO.popen(['zcat', file]).readlines[1..-1].each do |line|
line.chomp!
puts line, "\n\n"
end

关于ruby - 如何逐行读取 Ruby 1.8.7 中的 gzip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19578166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com