2017-09-01 33 views
0

我有一個閱讀excel電子表格的腳本。每個文件在被打開之前被複制到一個新的位置,確保文件中沒有其他人同時處於該位置。奇怪的是,有時我的腳本因爲文件不能在新的位置找到而中斷。Ruby - 如何等待文件在下一個動作之前完成移動?

# 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 aborted! 
Errno::ENOENT: No such file or directory @ rb_sysopen - 
C:\Users\ALilland\Downloads\tmp_dest\102035 Western Digital Job Status Reports.xls 
+0

我認爲命名約定是在這裏提出問題。你可以檢查控制檯File.exist?(路徑)?看看我們是否需要逃離一些特殊的字符,如空間或:或反斜槓。 – Mohanraj

回答

1

紅寶石顯示出來是單線程的,你不必等待文件被複制到目標路徑。

使用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 
相關問題