title: Context manager to remove tempfile
body: <p>I'm trying to write context manager to conditionally cleanup tempfile after processing. Simplified:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>Trying this script raises:</p>
  
  <pre><code>Traceback (most recent call last):
    File "C:\temp\test.py", line 18, in &lt;module&gt;
      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'
  </code></pre>
  
  <p>I would expect that tempfile is freed at the end of with statement cycle, while apparently it is not.</p>