私は現在堅牢なアトミックファイルコピー
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
は一時ファイルの名前が変更されているため使用できません。動作するはずです何
大きな 'try/except'でブロック全体を保護し、' tmp_h.name'を削除しようとしました(例外ハンドラで削除を保護してください) –