现在的位置: 首页 > 综合 > 正文

UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)

2015年03月22日 ⁄ 综合 ⁄ 共 897字 ⁄ 字号 评论关闭


在程序中调用封装的python的exe时,重定向exe的输出时,出现错误:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

在命令行方式下运行这个exe,正确输出。

在命令行方式下运行exe,>d:\temp.txt下,出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

百思不得其解,应该是pyhon的默认编码,与系统编码冲突。

在网上搜了一个解决方案,修改python安装目录下的lib中的site.py  文件。

def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

把 此处的第一个if 0:改为if 1:

抱歉!评论已关闭.