【发布时间】:2015-07-04 18:16:41
【问题描述】:
我使用常量 (FLOG) 作为句柄来写入我的日志。在给定的点上,我必须使用一个临时日志,然后将该内容附加到常规日志中,所有这些都具有相同的句柄,这是通过一堆方法使用的。
我的测试程序如下。关闭与临时日志关联的句柄“FLOG”后,当我将 FLOG 重新分配给新日志时,这会以某种方式重新打开临时日志,但我无法删除它。
有没有办法确保旧的临时文件保持关闭(所以我可以删除它)
# Pre-existing log:
final_log = "final_#{Time.now.strftime("%Y%m%d")}.txt"
#Writing something in it
File.open(final_log, "w+") { |file| file.write("This is the final log: #{final_log}\n") }
# temp log:
temp_log = "temp_#{Time.now.strftime("%Y%m%d")}.txt"
FLOG = File.new(temp_log, "w+")
# write some stuff in temp_log
FLOG.puts "Writing in temp_log named #{temp_log}"
# closing handle for temp_log
FLOG.close
# avoid constant reuse warning:
Object.send(:remove_const,'FLOG') if Object.const_defined?('FLOG')
# need to append temp_log content to final_log with handle FLOG
FLOG = File.open(final_log, "a+")
# appending old temp log to new log
File.open(temp_log, "r").readlines.each do |line|
puts "appending... #{line}"
FLOG.puts "appending... #{line}"
end
# closing handle
FLOG.close
# this tells me that 'temp_log' is somehow re-opened:
ObjectSpace.each_object(File) { |f| puts("3: #{temp_log} is open") if f.path == temp_log && !f.closed? }
File.delete(temp_log) # Cant do that:
# test_file2.rb:35:in `delete': Permission denied - temp_20150324.txt (Errno::EACCES)
【问题讨论】:
标签: ruby handle delete-file