Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a s
(prefer_stream=True)
| 36 | # Defined here as central function, so if we find better choices, we |
| 37 | # won't need to make changes all over IPython. |
| 38 | def getdefaultencoding(prefer_stream=True): |
| 39 | """Return IPython's guess for the default encoding for bytes as text. |
| 40 | |
| 41 | If prefer_stream is True (default), asks for stdin.encoding first, |
| 42 | to match the calling Terminal, but that is often None for subprocesses. |
| 43 | |
| 44 | Then fall back on locale.getpreferredencoding(), |
| 45 | which should be a sensible platform default (that respects LANG environment), |
| 46 | and finally to sys.getdefaultencoding() which is the most conservative option, |
| 47 | and usually UTF8 as of Python 3. |
| 48 | """ |
| 49 | enc = None |
| 50 | if prefer_stream: |
| 51 | enc = get_stream_enc(sys.stdin) |
| 52 | if not enc or enc=='ascii': |
| 53 | try: |
| 54 | # There are reports of getpreferredencoding raising errors |
| 55 | # in some cases, which may well be fixed, but let's be conservative here. |
| 56 | enc = locale.getpreferredencoding() |
| 57 | except Exception: |
| 58 | pass |
| 59 | enc = enc or sys.getdefaultencoding() |
| 60 | # On windows `cp0` can be returned to indicate that there is no code page. |
| 61 | # Since cp0 is an invalid encoding return instead cp1252 which is the |
| 62 | # Western European default. |
| 63 | if enc == 'cp0': |
| 64 | warnings.warn( |
| 65 | "Invalid code page cp0 detected - using cp1252 instead." |
| 66 | "If cp1252 is incorrect please ensure a valid code page " |
| 67 | "is defined for the process.", RuntimeWarning) |
| 68 | return 'cp1252' |
| 69 | return enc |
| 70 | |
| 71 | DEFAULT_ENCODING = getdefaultencoding() |
no test coverage detected