From 4eca2208bcfc46ece875dc73f74986431e2db7ad 2014-07-24 22:08:10 From: MinRK Date: 2014-07-24 22:08:10 Subject: [PATCH] Backport PR #6195: Close handle on new temporary files before returning filename On Windows, a file can only have one open writable handle at a time, so we need to close the one created by mkstemp before anything else can use that file. Closes gh-5946 --- diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 7202f86..22c5191 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -3036,6 +3036,7 @@ class InteractiveShell(SingletonConfigurable): self.tempdirs.append(dirname) handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) + os.close(handle) # On Windows, there can only be one open handle on a file self.tempfiles.append(filename) if data: diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index b01dc6d..c299cf8 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -417,6 +417,15 @@ class InteractiveShellTestCase(unittest.TestCase): ip.run_cell("d = 1/2", shell_futures=True) self.assertEqual(ip.user_ns['d'], 0) + def test_mktempfile(self): + filename = ip.mktempfile() + # Check that we can open the file again on Windows + with open(filename, 'w') as f: + f.write('abc') + + filename = ip.mktempfile(data='blah') + with open(filename, 'r') as f: + self.assertEqual(f.read(), 'blah') class TestSafeExecfileNonAsciiPath(unittest.TestCase):