From 516353d0c7585912aac8623469b12be159d4f15a 2013-09-09 00:23:26 From: MinRK Date: 2013-09-09 00:23:26 Subject: [PATCH] Backport PR #4163: Fix for incorrect default encoding on Windows. Whilst trying out rendering notebooks in a flask app under Apache on Windows I got the below error when simply trying to import `SlidesExporter` ```python mod_wsgi (pid=6260): Exception occurred processing WSGI script 'flask_test.wsgi'. Traceback (most recent call last): File "flask_test.py", line 81, in render_notebook from IPython.nbconvert.exporters import SlidesExporter File "c:\\dev\\code\\ipython\\IPython\\__init__.py", line 47, in from .terminal.embed import embed File "c:\\dev\\code\\ipython\\IPython\\terminal\\embed.py", line 32, in from IPython.terminal.interactiveshell import TerminalInteractiveShell File "c:\\dev\\code\\ipython\\IPython\\terminal\\interactiveshell.py", line 25, in from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC File "c:\\dev\\code\\ipython\\IPython\\core\\interactiveshell.py", line 59, in from IPython.core.prompts import PromptManager File "c:\\dev\\code\\ipython\\IPython\\core\\prompts.py", line 138, in HOME = py3compat.str_to_unicode(os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")) File "c:\\dev\\code\\ipython\\IPython\\utils\\py3compat.py", line 18, in decode return s.decode(encoding, "replace") LookupError: unknown encoding: cp0 ``` A little bit of [googling](http://bugs.python.org/issue6501) suggests that Windows returns 'cp0' to indicate there is no code page. This fix simply looks for this invalid value and replaces it with something valid. With this change it works for me. --- diff --git a/IPython/utils/encoding.py b/IPython/utils/encoding.py index cff1906..7eb7f2a 100644 --- a/IPython/utils/encoding.py +++ b/IPython/utils/encoding.py @@ -15,6 +15,7 @@ Utilities for dealing with text encodings #----------------------------------------------------------------------------- import sys import locale +import warnings # to deal with the possibility of sys.std* not being a stream at all def get_stream_enc(stream, default=None): @@ -51,6 +52,16 @@ def getdefaultencoding(): enc = locale.getpreferredencoding() except Exception: pass - return enc or sys.getdefaultencoding() + enc = enc or sys.getdefaultencoding() + # On windows `cp0` can be returned to indicate that there is no code page. + # Since cp0 is an invalid encoding return instead cp1252 which is the + # Western European default. + if enc == 'cp0': + warnings.warn( + "Invalid code page cp0 detected - using cp1252 instead." + "If cp1252 is incorrect please ensure a valid code page " + "is defined for the process.", RuntimeWarning) + return 'cp1252' + return enc DEFAULT_ENCODING = getdefaultencoding()