我正在尝试编写一个实用函数来打开三种不同类型的文件:.bz2、.gz 和 .txt。我不能只使用File.read
它,因为它给了我压缩文件的垃圾。我正在尝试使用Open3.popen3
,以便我可以给它一个不同的命令,但我得到一个“没有这样的文件或目录”错误,代码如下:
def file_info(file)
cmd = ''
if file.match("bz2") then
cmd = "bzcat #{file}"# | head -20"
elsif file.match("gz") then
cmd = "gunzip -c #{file}"
else
cmd = "cat #{file}"
end
puts "opening file #{file}"
Open3.popen3("#{cmd}", "r+") { |stdin, stdout, stderr|
puts "stdin #{stdin.inspect}"
stdin.read {|line|
puts "line is #{line}"
if line.match('^#') then
else
break
end
}
}
end
> No such file or directory - cat /tmp/test.txt
该文件确实存在。我cmd
尝试#{cmd}
在popen3 cmd
.
我决定硬编码它来执行txt文件,如下所示:
def file_info(file)
puts "opening file #{file}"
Open3.popen3("cat", file, "r+") { |stdin, stdout, stderr|
puts "stdin #{stdin.inspect}"
stdin.read {|line|
puts "line is #{line}"
if line.match('^#') then
else
break
end
}
}
end
这让我回来了:
stdin #<IO:fd 6>
not opened for reading
我究竟做错了什么?
当我做:
Open3.popen3("cat",file) { |stdin, stdout, stderr|
puts "stdout is #{stdout.inspect}"
stdout.read {|line|
puts "line is #{line}"
if line.match('^#') then
puts "found line #{line}"
else
break
end
}
}
我没有收到任何错误,并且打印了 STDOUT 行,但没有一行语句打印出任何内容。
在尝试了几种不同的方法后,我想出的解决方案是:
cmd = Array.new
if file.match(/\.bz2\z/) then
cmd = [ 'bzcat', file ]
elsif file.match(/\.gz\z/) then
cmd = [ 'gunzip', '-c', file ]
else
cmd = [ 'cat', file ]
end
Open3.popen3(*cmd) do |stdin, stdout, stderr|
puts "stdout is #{stdout}"
stdout.each do |line|
if line.match('^#') then
puts "line is #{line}"
else
break
end
end
end