【问题标题】:Ruby - how do I wait for a file to finish moving before the next action?Ruby - 如何在下一个操作之前等待文件完成移动?
【发布时间】:2017-09-01 23:09:59
【问题描述】:

我有一个正在读取 excel 电子表格的脚本。每个文件在打开之前都会被复制到一个新位置,以确保文件中同时没有其他人。奇怪的是,有时我的脚本会因为在新位置找不到文件而中断。

# copy the file to a new destination
# the file is originating on a windows file server, 
# the destination is my local downloads folder on a windows machine.  
FileUtils.cp(some_filepath, destination_path)
# the next line gives an error, because the file doesnt exist at its location yet
Spreadsheet.open(file_at_new_destination) 

我已尝试执行until 块,在脚本继续执行之前检查文件是否存在,但即使这样也不起作用,只会永远运行。

# check if file exists
until File.exist?(file_at_new_destination) do
  print '.'
end

如何确保脚本在文件完成移动之前不会继续运行?

这是我的 rake 任务中出现的错误

rake aborted!
Errno::ENOENT: No such file or directory @ rb_sysopen -
C:\Users\ALilland\Downloads\tmp_dest\102035 Western Digital Job Status Reports.xls

【问题讨论】:

  • 我认为命名约定是这里的问题所在。你可以检查控制台 File.exist 吗?(路径)?看看我们是否需要转义一些特殊字符,如空格或:或反斜杠。

标签: ruby windows


【解决方案1】:

Ruby 是单线程的,您不必等待文件被复制到目标路径。

在复制包含所有子目录的目录时,请使用 cp_r 而不是 cp

# copy directory to destination directory recursively.    
FileUtils.cp_r(some_filepath, destination_path)
if File.exist?(file_at_new_destination)
 Spreadsheet.open(file_at_new_destination)
end

【讨论】:

    猜你喜欢
    • 2017-02-15
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多