Skip to content

Commit

Permalink
Fix printing of emoji on Windows when stdout is redirected
Browse files Browse the repository at this point in the history
This is most apparent when black is run via pre-commit which does
`subprocess.Popen(stdout=PIPE)`.

One option around this would be to instruct users to set `PYTHONUTF8=1`,
but that is not a very good approach, as basically everything supports
UTF-8 these days.

This fix was inspired by pycln and hadialqattan/pycln#54
  • Loading branch information
ashb committed Nov 3, 2022
1 parent 2704dc7 commit 8407f29
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@

<!-- Changes to Black's terminal output and error messages -->

- Force output messages to always be UTF-8 on Windows (so we can see the emoji), even if terminal is redirected or captured (#3374)

### _Blackd_

<!-- Changes to blackd -->
Expand Down
6 changes: 6 additions & 0 deletions src/black/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1393,6 +1393,12 @@ def patch_click() -> None:


def patched_main() -> None:
#: Fixes errors with emoji in Windows terminals when output is redirected (i.e. pre-commit)
#: https://github.com/psf/black/issues/3156
if "pytest" not in sys.modules and sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") # pragma: nocover
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") # pragma: nocover

# PyInstaller patches multiprocessing to need freeze_support() even in non-Windows
# environments so just assume we always need to call it if frozen.
if getattr(sys, "frozen", False):
Expand Down

0 comments on commit 8407f29

Please sign in to comment.