2017-04-13 43 views
1

我現在有強大的原子文件複製

def _atomic_copyfile(src, dst, overwrite): 
    with tempfile.NamedTemporaryFile(dir=os.path.dirname(dst), 
            delete=False) as tmp_h: 
     with open(src, 'rb') as src_fd: 
      shutil.copyfileobj(fsrc=src_fd, 
           fdst=tmp_h) 
    if overwrite: 
     # works both on Windows and Linux from Python 3.3+, os.rename raises an 
     # exception on Windows if the file exists 
     os.replace(src=tmp_h.name, 
        dst=dst) 
    else: 
     if not os.path.exists(dst): 
      os.rename(src=tmp_h.name, 
         dst=dst) 

如何讓我的臨時文件tmp_h自動,如果有異常拋出或去除一個信號被捕獲?

請注意,我不能使用delete=True,因爲臨時文件已重命名。

+0

用大'try/except'保護整個塊並嘗試刪除'tmp_h.name'(保護由異常處理程序移除) –

回答

0

什麼應該工作(我通常不會使用try/except:沒有任何異常,但在它適用的話,那也許是因爲你想添加一個消息,回溯,無論在except情況下):

def _atomic_copyfile(src, dst, overwrite): 
    try: 
     with tempfile.NamedTemporaryFile(dir=os.path.dirname(dst), 
             delete=False) as tmp_h: 
     # your current code 
    except: 
     # maybe print something here to notify that an error occured 
     # instead of masking it 
     pass 
    finally: 
     try: 
      os.remove(tmp_h.name) 
     except: 
      pass 

finally部分中的代碼嘗試刪除該文件。如果失敗,則捕獲異常並且什麼也不做(例如,如果該文件不存在或被重命名,或者甚至:tmp_h變量還不存在)

os.remove當然,即使文件已經存在,但不太可能,因爲你不在with上下文中,該文件已經關閉。

+1

你確定'tmp_h'將在finally範圍? –

+0

不,我不確定,但我的回答覆蓋了它,「甚至:tmp_h變量還沒有存在」:你會得到一個異常,你會像其他任何一個陷阱 –