创建临时文件而不在 Ruby 中打开它
有没有办法创建临时文件而不打开它?我必须运行一个可执行文件,将其输出重定向到一个文件,然后读取并保存它。解析那个。 tempfile
创建的所有内容都已打开,这会触发错误,因为文件已锁定。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还可以使用 Dir::Tmpname
路径将包含唯一路径
请参阅 https ://github.com/ruby/ruby/blob/ruby_1_9_3/lib/tmpdir.rb#L116
You can also use Dir::Tmpname
path will contain unique path
See https://github.com/ruby/ruby/blob/ruby_1_9_3/lib/tmpdir.rb#L116
我没有收到错误:
话又说回来,临时文件看起来并不是非常临时。
是所有程序都会出现此错误,还是仅某个特定程序会出现该错误?另外,您可以发布导致问题的代码以及您得到的错误回溯吗?
I didn't get an error:
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?
使用 FileUtils.touch 是可接受的解决方案吗?您可以触摸文件并在完成所需操作后将其删除。
Is using FileUtils.touch acceptable solution? You can touch a file and delete it once you are done with whatever you want.
您可能想使用管道。
如果可执行文件是从 ruby 程序启动的,请考虑使用 IO.popen。
如果它们是不同的进程,您可以尝试 命名管道。
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.
@timfjord 的答案有效。但如果你不需要块尝试:
The @timfjord's answer works. But if you don't need a block try: