runtime_compat.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Runtime compatibility helpers.
  5. """
  6. from __future__ import annotations
  7. import os
  8. import sys
  9. def enable_windows_utf8_stdio(*, skip_in_pytest: bool = False) -> bool:
  10. """Enable UTF-8 stdio wrappers on Windows.
  11. Returns:
  12. True if wrapping was applied, False otherwise.
  13. """
  14. if sys.platform != "win32":
  15. return False
  16. if skip_in_pytest and os.environ.get("PYTEST_CURRENT_TEST"):
  17. return False
  18. stdout_encoding = str(getattr(sys.stdout, "encoding", "") or "").lower()
  19. stderr_encoding = str(getattr(sys.stderr, "encoding", "") or "").lower()
  20. if stdout_encoding == "utf-8" and stderr_encoding == "utf-8":
  21. return False
  22. try:
  23. import io
  24. if hasattr(sys.stdout, "buffer"):
  25. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
  26. if hasattr(sys.stderr, "buffer"):
  27. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
  28. return True
  29. except Exception:
  30. return False