diff -r 7230978647a8 Lib/tempfile.py --- a/Lib/tempfile.py Fri Sep 26 12:33:06 2014 -0400 +++ b/Lib/tempfile.py Fri Sep 26 17:01:28 2014 -0400 @@ -212,6 +212,16 @@ raise FileExistsError(_errno.EEXIST, "No usable temporary file name found") +def _sanitize_dir(dir): + """A helper function to sanitize 'dir' argument.""" + + if dir is None: + return gettempdir() + else: + # Call abspath to resolve relative paths to absolute ones, + # see issue #20267. + return _os.path.abspath(dir) + # User visible interfaces. @@ -259,8 +269,7 @@ Caller is responsible for deleting the file when done with it. """ - if dir is None: - dir = gettempdir() + dir = _sanitize_dir(dir) if text: flags = _text_openflags @@ -283,8 +292,7 @@ Caller is responsible for deleting the directory when done with it. """ - if dir is None: - dir = gettempdir() + dir = _sanitize_dir(dir) names = _get_candidate_names() @@ -317,8 +325,7 @@ ## _warn("mktemp is a potential security risk to your program", ## RuntimeWarning, stacklevel=2) - if dir is None: - dir = gettempdir() + dir = _sanitize_dir(dir) names = _get_candidate_names() for seq in range(TMP_MAX): @@ -447,8 +454,7 @@ when it is closed unless the 'delete' argument is set to False. """ - if dir is None: - dir = gettempdir() + dir = _sanitize_dir(dir) flags = _bin_openflags @@ -495,8 +501,7 @@ """ global _O_TMPFILE_WORKS - if dir is None: - dir = gettempdir() + dir = _sanitize_dir(dir) flags = _bin_openflags if _O_TMPFILE_WORKS: diff -r 7230978647a8 Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Fri Sep 26 12:33:06 2014 -0400 +++ b/Lib/test/test_tempfile.py Fri Sep 26 17:01:28 2014 -0400 @@ -1264,6 +1264,18 @@ self.assertEqual(name, d.name) self.assertFalse(os.path.exists(name)) + def test_different_cwd_upon_creation(self): # See issue #20267 + # Relative paths are supported + old_cwd = os.getcwd() + try: + new_cwd = os.path.dirname(tempfile.mkdtemp()) + os.chdir(new_cwd) + d = self.do_create(dir='.') + finally: + os.chdir(old_cwd) + + self.assertTrue(new_cwd in d.name) + d.cleanup() def test_main(): support.run_unittest(__name__)