diff options
author | Inada Naoki <songofacandy@gmail.com> | 2022-07-24 11:42:11 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-07-24 11:42:11 +0900 |
commit | 5c7f3bcdafedd60a385e8ca5403bc6b0b7a862b3 (patch) | |
tree | 20edad2c555adf96dbf4350a3cc88f9742b667e4 /Lib | |
parent | a2fbc511985f77c16c0f4a6fc6d3da9ab81a86b7 (diff) | |
download | cpython-5c7f3bcdafedd60a385e8ca5403bc6b0b7a862b3.tar.gz cpython-5c7f3bcdafedd60a385e8ca5403bc6b0b7a862b3.zip |
gh-93157: Fix fileinput didn't support `errors` in `inplace` mode (GH-95128)
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/fileinput.py | 9 | ||||
-rw-r--r-- | Lib/test/test_fileinput.py | 10 |
2 files changed, 16 insertions, 3 deletions
diff --git a/Lib/fileinput.py b/Lib/fileinput.py index 9f41c18510d..e234dc9ea65 100644 --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -335,18 +335,21 @@ class FileInput: 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: diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index 819200010a2..ac20c74baa0 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -326,6 +326,16 @@ class FileInputTests(BaseTests, unittest.TestCase): 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") |