Skip to content

Commit 80f0707

Browse files
stefanhoelzlStefan HoelzlBoboTiG
authored
bpo-44666: Use default encoding as fallback for compile_file (pythonGH-27236)
When sys.stdout.encoding is None compile_file will fall back to sys.getdefaultencoding to encode/decode error messages. Co-authored-by: Stefan Hoelzl <stefan.hoelzl@posteo.de> Co-authored-by: Mickaël Schoentgen <contact@tiger-222.fr>
1 parent 7cad0be commit 80f0707

File tree

4 files changed

+13
-3
lines changed

4 files changed

+13
-3
lines changed

Lib/compileall.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,9 +254,8 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
254254
else:
255255
print('*** ', end='')
256256
# escape non-printable characters in msg
257-
msg = err.msg.encode(sys.stdout.encoding,
258-
errors='backslashreplace')
259-
msg = msg.decode(sys.stdout.encoding)
257+
encoding = sys.stdout.encoding or sys.getdefaultencoding()
258+
msg = err.msg.encode(encoding, errors='backslashreplace').decode(encoding)
260259
print(msg)
261260
except (SyntaxError, UnicodeError, OSError) as e:
262261
success = False

Lib/test/test_compileall.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,14 @@ def test_no_pycache_in_non_package(self):
169169
compileall.compile_file(data_file)
170170
self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
171171

172+
173+
def test_compile_file_encoding_fallback(self):
174+
# Bug 44666 reported that compile_file failed when sys.stdout.encoding is None
175+
self.add_bad_source_file()
176+
with contextlib.redirect_stdout(io.StringIO()):
177+
self.assertFalse(compileall.compile_file(self.bad_source_path))
178+
179+
172180
def test_optimize(self):
173181
# make sure compiling with different optimization settings than the
174182
# interpreter's creates the correct file names

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,7 @@ Fredrik Håård
794794
Florian Höch
795795
Oleg Höfling
796796
Robert Hölzl
797+
Stefan Hölzl
797798
Catalin Iacob
798799
Mihai Ibanescu
799800
Ali Ikinci
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed issue in :func:`compileall.compile_file` when ``sys.stdout`` is redirected.
2+
Patch by Stefan Hölzl.

0 commit comments

Comments
 (0)