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'
나는, 그 임시 파일 문 사이클의 끝에서 해제됩니다 기대.
아 좋은 :
또 다른 옵션은 상황에 관리자로 파일 객체를 래핑하는 것입니다. 감사 – vedar