8000 gh-93157: Fix fileinput didn't support `errors` in `inplace` mode (GH… · python/cpython@4a682b4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4a682b4

Browse files
gh-93157: Fix fileinput didn't support errors in inplace mode (GH-95128)
(cherry picked from commit 5c7f3bc) Co-authored-by: Inada Naoki <songofacandy@gmail.com>
1 parent e71e6e2 commit 4a682b4

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

Lib/fileinput.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,18 +355,21 @@ def _readline(self):
355355
pass
356356
# The next few lines may raise OSError
357357
os.rename(self._filename, self._backupfilename)
358-
self._file = open(self._backupfilename, self._mode, encoding=encoding)
358+
self._file = open(self._backupfilename, self._mode,
359+
encoding=encoding, errors=self._errors)
359360
try:
360361
perm = os.fstat(self._file.fileno()).st_mode
361362
except OSError:
362-
self._output = open(self._filename, self._write_mode, encoding=encoding)
363+
self._output = open(self._filename, self._write_mode,
364+
encoding=encoding, errors=self._errors)
363365
else:
364366
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
365367
if hasattr(os, 'O_BINARY'):
366368
mode |= os.O_BINARY
367369

368370
fd = os.open(self._filename, mode, perm)
369-
self._output = os.fdopen(fd, self._write_mode, encoding=encoding)
371+
self._output = os.fdopen(fd, self._write_mode,
372+
encoding=encoding, errors=self._errors)
370373
try:
371374
os.chmod(self._filename, perm)
372375
except OSError:

Lib/test/test_fileinput.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,16 @@ def test_inplace_binary_write_mode(self):
336336
with open(temp_file, 'rb') as f:
337337
self.assertEqual(f.read(), b'New line.')
338338

339+
def test_inplace_encoding_errors(self):
340+
temp_file = self.writeTmp(b'Initial text \x88', mode='wb')
341+
with FileInput(temp_file, inplace=True,
342+
encoding="ascii", errors="replace") as fobj:
343+
line = fobj.readline()
344+
self.assertEqual(line, 'Initial text \ufffd')
345+
print("New line \x88")
346+
with open(temp_file, 'rb') as f:
347+
self.assertEqual(f.read().rstrip(b'\r\n'), b'New line ?')
348+
339349
def test_file_hook_backward_compatibility(self):
340350
def old_hook(filename, mode):
341351
return io.StringIO("I used to receive only filename and mode")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`fileinput` module didn't support ``errors`` option when
2+
``inplace`` is true.

0 commit comments

Comments
 (0)
0