Commit 973618a
authored
Gracefully handle encoding errors when writing to stdout (#18292)
Fixes #12692
Sets the [encoding error
handler](https://docs.python.org/3/library/codecs.html#error-handlers)
for `stdout` to `"backslashreplace"`. This prevents mypy from crashing
if an error message has a character that can't be represented by the
current I/O encoding.
No change is made to `stderr` since its default is already
`"backslashreplace"`.
**Before**
```shell
$ PYTHONIOENCODING=ascii mypy -c "x=γ"
Traceback (most recent call last):
...
UnicodeEncodeError: 'ascii' codec can't encode character '\u03b3' in position 50: ordinal not in range(128)
```
**After:**
```shell
$ PYTHONIOENCODING=ascii mypy -c "x=γ"
<string>:1: error: Name "\u03b3" is not defined [name-defined]
Found 1 error in 1 file (checked 1 source file)
```
Externally setting the error handler to something other than `"strict"`
still works. For example:
```shell
$ PYTHONIOENCODING=ascii:namereplace mypy -c "x=γ"
<string>:1: error: Name "\N{GREEK SMALL LETTER GAMMA}" is not defined [name-defined]
Found 1 error in 1 file (checked 1 source file)
```1 parent 7abcffe commit 973618a
1 file changed
Lines changed: 5 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
| 12 | + | |
12 | 13 | | |
13 | 14 | | |
14 | 15 | | |
| |||
74 | 75 | | |
75 | 76 | | |
76 | 77 | | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
77 | 82 | | |
78 | 83 | | |
79 | 84 | | |
| |||
0 commit comments