2016-06-24 2 views
0

처리 후 임시 파일을 조건부로 정리하기 위해 컨텍스트 관리자를 작성하려고합니다. 간체 :임시 파일을 제거하는 컨텍스트 관리자

import os 
from contextlib import contextmanager 
from subprocess import Popen 
from tempfile import NamedTemporaryFile 


@contextmanager 
def temp(cleanup=True): 
    tmp = NamedTemporaryFile(delete=False) 
    try: 
     yield tmp 
    finally: 
     cleanup and os.remove(tmp.name) 

with temp() as tmp: 
    tmp.write(b'Hi') 
    p = Popen(['cmd', '/c', 'type', tmp.name]) 
    p.wait() 

노력이 스크립트는 제기 분명히 그렇지 않은 동안

Traceback (most recent call last): 
    File "C:\temp\test.py", line 18, in <module> 
    p.wait() 
    File "C:\Python35\lib\contextlib.py", line 66, in __exit__ 
    next(self.gen) 
    File "C:\temp\test.py", line 13, in temp 
    cleanup and os.remove(tmp.name) 
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Temp\\tmp79su99sg' 

나는, 그 임시 파일 문 사이클의 끝에서 해제됩니다 기대.

답변

1

실제로 파일을 제거하려고하면 파일이 열려 있습니다. 당신은 그것을 제거하기 전에 먼저 파일을 닫해야합니다 :

@contextmanager 
def temp(cleanup=True): 
    tmp = NamedTemporaryFile(delete=False) 
    try: 
     with tmp: 
      yield tmp 
    finally: 
     cleanup and os.remove(tmp.name) 
+0

아 좋은 :

@contextmanager def temp(cleanup=True): tmp = NamedTemporaryFile(delete=False) try: yield tmp finally: tmp.close() #closes the file, so we can right remove it cleanup and os.remove(tmp.name) 

또 다른 옵션은 상황에 관리자로 파일 객체를 래핑하는 것입니다. 감사 – vedar

관련 문제