2013-10-10 21 views
22

Có cách nào để tạo thư mục tạm thời trong trình quản lý ngữ cảnh bằng Python 2.7 không?tempfile.TemporaryDirectory quản lý ngữ cảnh bằng Python 2.7

with tempfile.TemporaryDirectory() as temp_dir: 
    # modify files in this dir 

# here the temporary diretory does not exist any more. 
+0

Xem https://stackoverflow.com/q/6884991 cho làm thế nào để làm điều này bằng tay. –

Trả lời

18

Một lựa chọn khác là "backports.tempfile" gói trên pypi: https://pypi.python.org/pypi/backports.tempfile

Trích dẫn mô tả của dự án: "Gói này cung cấp backports các tính năng mới trong mô-đun tempfile Python dưới không gian tên backports. "

Cài đặt với:

pip install backports.tempfile 

Sau đó, sử dụng nó trong kịch bản của bạn:

from backports import tempfile 
with tempfile.TemporaryDirectory() as temp_dir: 
    # modify files in this dir 
# here the temporary directory does not exist any more. 
+0

Tôi thích điều này hơn copy + trích đoạn trích. Cảm ơn bạn. Tôi hy vọng câu hỏi của tôi hiện không nhận được phiếu bầu, vì tôi thích thư viện hơn. Câu hỏi liên quan đến thư viện nên truy cập http://softwarerecs.stackexchange.com/ ... BTW: Tôi đang nói đùa, tôi không hiểu tại sao trang web sofwarerec lại tồn tại. Tại sao không đặt câu hỏi về các khuyến nghị phần mềm trên StackOverFlow ... – guettli

+2

Thật đáng lo ngại, backport không bí danh tất cả những thứ 'tempfile' hiện có để bạn có thể cần cả hai. –

27

tempfile.TemporaryDirectory() đã được thêm vào thư viện chuẩn tempfile bằng Python 3.2

Đó là một wrapper đơn giản cho tempfile.mkdtemp. Nó được mã hóa bằng Python thuần túy và có thể dễ dàng chuyển sang Python 2.7.

Ví dụ:

from __future__ import print_function 

import warnings as _warnings 
import os as _os 

from tempfile import mkdtemp 

class TemporaryDirectory(object): 
    """Create and return a temporary directory. This has the same 
    behavior as mkdtemp but can be used as a context manager. For 
    example: 

     with TemporaryDirectory() as tmpdir: 
      ... 

    Upon exiting the context, the directory and everything contained 
    in it are removed. 
    """ 

    def __init__(self, suffix="", prefix="tmp", dir=None): 
     self._closed = False 
     self.name = None # Handle mkdtemp raising an exception 
     self.name = mkdtemp(suffix, prefix, dir) 

    def __repr__(self): 
     return "<{} {!r}>".format(self.__class__.__name__, self.name) 

    def __enter__(self): 
     return self.name 

    def cleanup(self, _warn=False): 
     if self.name and not self._closed: 
      try: 
       self._rmtree(self.name) 
      except (TypeError, AttributeError) as ex: 
       # Issue #10188: Emit a warning on stderr 
       # if the directory could not be cleaned 
       # up due to missing globals 
       if "None" not in str(ex): 
        raise 
       print("ERROR: {!r} while cleaning up {!r}".format(ex, self,), 
         file=_sys.stderr) 
       return 
      self._closed = True 
      if _warn: 
       self._warn("Implicitly cleaning up {!r}".format(self), 
          ResourceWarning) 

    def __exit__(self, exc, value, tb): 
     self.cleanup() 

    def __del__(self): 
     # Issue a ResourceWarning if implicit cleanup needed 
     self.cleanup(_warn=True) 

    # XXX (ncoghlan): The following code attempts to make 
    # this class tolerant of the module nulling out process 
    # that happens during CPython interpreter shutdown 
    # Alas, it doesn't actually manage it. See issue #10188 
    _listdir = staticmethod(_os.listdir) 
    _path_join = staticmethod(_os.path.join) 
    _isdir = staticmethod(_os.path.isdir) 
    _islink = staticmethod(_os.path.islink) 
    _remove = staticmethod(_os.remove) 
    _rmdir = staticmethod(_os.rmdir) 
    _warn = _warnings.warn 

    def _rmtree(self, path): 
     # Essentially a stripped down version of shutil.rmtree. We can't 
     # use globals because they may be None'ed out at shutdown. 
     for name in self._listdir(path): 
      fullname = self._path_join(path, name) 
      try: 
       isdir = self._isdir(fullname) and not self._islink(fullname) 
      except OSError: 
       isdir = False 
      if isdir: 
       self._rmtree(fullname) 
      else: 
       try: 
        self._remove(fullname) 
       except OSError: 
        pass 
     try: 
      self._rmdir(path) 
     except OSError: 
      pass 

import os 
with TemporaryDirectory() as tmp_dir: 
    print("Temporary directory path: %s" % tmp_dir) 
    print(os.path.isdir(tmp_dir)) 

# here the temporary diretory does not exist any more. 
print(os.path.isdir(tmp_dir)) 
+0

Nếu các dòng '_ = staticmethod (điều)' không hoạt động, có lẽ chúng sẽ bị loại bỏ? –

+0

Có thiếu 'sys nhập _sys' cho' print (... file = _sys.stderr) 'không? – hooblei

+0

Liên kết nguồn: [tempfile.py] (https://github.com/python/cpython/blob/master/Lib/tempfile.py) Mã phức tạp là do cố gắng dọn dẹp trong quá trình hoàn thành, nếu trình quản lý ngữ cảnh chưa được đóng đúng cách khi tắt máy. Điều này dẫn đến [Vấn đề # 22427] (https://bugs.python.org/issue22427) và đã được đơn giản hóa. –

Các vấn đề liên quan