Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-93157: Fix fileinput didn't support errors in inplace mode #95128

Merged
merged 3 commits into from
Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions Lib/fileinput.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,18 +335,21 @@ def _readline(self):
pass
# The next few lines may raise OSError
os.rename(self._filename, self._backupfilename)
self._file = open(self._backupfilename, self._mode, encoding=encoding)
self._file = open(self._backupfilename, self._mode,
encoding=encoding, errors=self._errors)
try:
perm = os.fstat(self._file.fileno()).st_mode
except OSError:
self._output = open(self._filename, self._write_mode, encoding=encoding)
self._output = open(self._filename, self._write_mode,
encoding=encoding, errors=self._errors)
else:
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY

fd = os.open(self._filename, mode, perm)
self._output = os.fdopen(fd, self._write_mode, encoding=encoding)
self._output = os.fdopen(fd, self._write_mode,
encoding=encoding, errors=self._errors)
try:
os.chmod(self._filename, perm)
except OSError:
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_fileinput.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,16 @@ def test_inplace_binary_write_mode(self):
with open(temp_file, 'rb') as f:
self.assertEqual(f.read(), b'New line.')

def test_inplace_encoding_errors(self):
temp_file = self.writeTmp(b'Initial text \x88', mode='wb')
with FileInput(temp_file, inplace=True,
encoding="ascii", errors="replace") as fobj:
line = fobj.readline()
self.assertEqual(line, 'Initial text \ufffd')
print("New line \x88")
with open(temp_file, 'rb') as f:
self.assertEqual(f.read().rstrip(b'\r\n'), b'New line ?')

def test_file_hook_backward_compatibility(self):
def old_hook(filename, mode):
return io.StringIO("I used to receive only filename and mode")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :mod:`fileinput` module didn't support ``errors`` option when
``inplace`` is true.