Skip to content

Commit

Permalink
Backport PR #6911: don't use text mode in mkstemp
Browse files Browse the repository at this point in the history
causes double-encoding of newlines, preventing newline arg from having desired effect,
and resulting in CRCRLF line endings on Windows.

closes #6599
  • Loading branch information
minrk committed Nov 12, 2014
1 parent 4df122d commit f296212
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
2 changes: 1 addition & 1 deletion IPython/utils/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
39 changes: 38 additions & 1 deletion IPython/utils/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,41 @@ class CustomExc(Exception): pass
f.write(u'written from symlink')

with stdlib_io.open(f1, 'r') as f:
nt.assert_equal(f.read(), u'written from symlink')
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)

0 comments on commit f296212

Please sign in to comment.