encoding.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # coding: utf-8
  2. """
  3. Utilities for dealing with text encodings
  4. """
  5. from __future__ import annotations
  6. # -----------------------------------------------------------------------------
  7. # Copyright (C) 2008-2012 The IPython Development Team
  8. #
  9. # Distributed under the terms of the BSD License. The full license is in
  10. # the file COPYING, distributed as part of this software.
  11. # -----------------------------------------------------------------------------
  12. # -----------------------------------------------------------------------------
  13. # Imports
  14. # -----------------------------------------------------------------------------
  15. import sys
  16. import locale
  17. import warnings
  18. from typing import Any, Literal
  19. # to deal with the possibility of sys.std* not being a stream at all
  20. def get_stream_enc(stream: Any, default: str | None = None) -> str | None:
  21. """Return the given stream's encoding or a default.
  22. There are cases where ``sys.std*`` might not actually be a stream, so
  23. check for the encoding attribute prior to returning it, and return
  24. a default if it doesn't exist or evaluates as False. ``default``
  25. is None if not provided.
  26. """
  27. if not hasattr(stream, "encoding") or not stream.encoding:
  28. return default
  29. else:
  30. return stream.encoding
  31. _sentinel: object = object()
  32. # Less conservative replacement for sys.getdefaultencoding, that will try
  33. # to match the environment.
  34. # Defined here as central function, so if we find better choices, we
  35. # won't need to make changes all over IPython.
  36. def getdefaultencoding(prefer_stream: object | bool = _sentinel) -> str:
  37. """Return IPython's guess for the default encoding for bytes as text.
  38. If prefer_stream is True (default), asks for stdin.encoding first,
  39. to match the calling Terminal, but that is often None for subprocesses.
  40. Then fall back on locale.getpreferredencoding(),
  41. which should be a sensible platform default (that respects LANG environment),
  42. and finally to sys.getdefaultencoding() which is the most conservative option,
  43. and usually UTF8 as of Python 3.
  44. """
  45. if prefer_stream is not _sentinel:
  46. warnings.warn(
  47. "getpreferredencoding(prefer_stream=) argument is deprecated since "
  48. "IPython 9.0, getdefaultencoding() will take no argument in the "
  49. "future. If you rely on `prefer_stream`, please open an issue on "
  50. "the IPython repo.",
  51. DeprecationWarning,
  52. stacklevel=2,
  53. )
  54. prefer_stream = True
  55. enc: str | None = None
  56. if prefer_stream:
  57. enc = get_stream_enc(sys.stdin)
  58. if not enc or enc == "ascii":
  59. try:
  60. # There are reports of getpreferredencoding raising errors
  61. # in some cases, which may well be fixed, but let's be conservative here.
  62. enc = locale.getpreferredencoding()
  63. except Exception:
  64. pass
  65. enc = enc or sys.getdefaultencoding()
  66. # On windows `cp0` can be returned to indicate that there is no code page.
  67. # Since cp0 is an invalid encoding return instead cp1252 which is the
  68. # Western European default.
  69. if enc == "cp0":
  70. warnings.warn(
  71. "Invalid code page cp0 detected - using cp1252 instead."
  72. "If cp1252 is incorrect please ensure a valid code page "
  73. "is defined for the process.",
  74. RuntimeWarning,
  75. )
  76. return "cp1252"
  77. return enc
  78. DEFAULT_ENCODING = getdefaultencoding()