From abace052016a98a8be7b8ca0e6359186e11094b2 2014-11-12 22:17:32 From: Min RK Date: 2014-11-12 22:17:32 Subject: [PATCH] don't use text mode in mkstemp causes double-encoding of newlines, preventing newline arg from having desired effect. --- diff --git a/IPython/utils/io.py b/IPython/utils/io.py index 422f655..df1e39e 100644 --- a/IPython/utils/io.py +++ b/IPython/utils/io.py @@ -267,7 +267,7 @@ def atomic_writing(path, text=True, encoding='utf-8', **kwargs): path = os.path.join(os.path.dirname(path), os.readlink(path)) dirname, basename = os.path.split(path) - handle, tmp_path = tempfile.mkstemp(prefix=basename, dir=dirname, text=text) + handle, tmp_path = tempfile.mkstemp(prefix=basename, dir=dirname) if text: fileobj = io.open(handle, 'w', encoding=encoding, **kwargs) else: diff --git a/IPython/utils/tests/test_io.py b/IPython/utils/tests/test_io.py index a76179f..023c964 100644 --- a/IPython/utils/tests/test_io.py +++ b/IPython/utils/tests/test_io.py @@ -175,4 +175,41 @@ def test_atomic_writing(): f.write(u'written from symlink') with stdlib_io.open(f1, 'r') as f: - nt.assert_equal(f.read(), u'written from symlink') \ No newline at end of file + nt.assert_equal(f.read(), u'written from symlink') + +def test_atomic_writing_newlines(): + with TemporaryDirectory() as td: + path = os.path.join(td, 'testfile') + + lf = u'a\nb\nc\n' + plat = lf.replace(u'\n', os.linesep) + crlf = lf.replace(u'\n', u'\r\n') + + # test default + with stdlib_io.open(path, 'w') as f: + f.write(lf) + with stdlib_io.open(path, 'r', newline='') as f: + read = f.read() + nt.assert_equal(read, plat) + + # test newline=LF + with stdlib_io.open(path, 'w', newline='\n') as f: + f.write(lf) + with stdlib_io.open(path, 'r', newline='') as f: + read = f.read() + nt.assert_equal(read, lf) + + # test newline=CRLF + with atomic_writing(path, newline='\r\n') as f: + f.write(lf) + with stdlib_io.open(path, 'r', newline='') as f: + read = f.read() + nt.assert_equal(read, crlf) + + # test newline=no convert + text = u'crlf\r\ncr\rlf\n' + with atomic_writing(path, newline='') as f: + f.write(text) + with stdlib_io.open(path, 'r', newline='') as f: + read = f.read() + nt.assert_equal(read, text)