Create a tempfile without opening it in Ruby

ぐ巨炮叔叔 提交于 2019-12-30 06:18:10

问题


Is there a way to create a tempfile, without having it opened? I have to run an executable, redirect it's output to a file, and then read & parse that. Everything created by tempfile is already opened, and this triggers an error , because the file is locked.


回答1:


Is using FileUtils.touch acceptable solution? You can touch a file and delete it once you are done with whatever you want.




回答2:


You can also use Dir::Tmpname

Dir::Tmpname.create('your_application_prefix') { |path| puts path }

path will contain unique path

See https://github.com/ruby/ruby/blob/ruby_1_9_3/lib/tmpdir.rb#L116




回答3:


I didn't get an error:

Andrew-Grimms-MacBook-Pro:~ agrimm$ irb
>> require "tempfile"
=> true
>> tempfile = Tempfile.new("temporary_file.txt", "/tmp")
=> #<File:/tmp/temporary_file.txt20110622-648-pkynjw-0>
>> tempfile.close
=> nil
>> system("echo foo > #{tempfile.path}")
=> true
>> system("cat #{tempfile.path}")
foo
=> true
>> tempfile.path
=> "/tmp/temporary_file.txt20110622-648-pkynjw-0"
>> exit
Andrew-Grimms-MacBook-Pro:~ agrimm$ cat /tmp/temporary_file.txt20110622-648-pkynjw-0
foo

Then again, the temporary file doesn't seem awfully temporary.

Does the error happen with all programs, or just a specific program? Also, can you post the code that causes the problem, and what error backtrace you get?




回答4:


You may want to use pipes.

If the executable is started from your ruby program, consider using IO.popen.

If they're different processes, you can try named pipes.



来源:https://stackoverflow.com/questions/6437655/create-a-tempfile-without-opening-it-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!