Skip to main content
 首页 » 编程设计

python之部署 Python 应用程序时出现 Unicode 编码错误

2025年05月04日10lexus

我有一个简单的 python/pyqt 应用程序,它正在将数据插入到 SQLITE 数据库表中, 一些条目包含特殊字符,例如变音符号。 我使用 eclipse 进行了开发,对其进行了测试并成功地插入了所有数据而没有任何错误。 然后我决定为我的应用程序创建一个可执行文件。我正在使用 py2exe 创建可执行文件。我的 setup.py 如下所示

from distutils.core import setup 
import py2exe 
import os 
includes=["sqlite3","sip","PyQt4", "PyQt4.QtGui"] 
excludes=[] 
packages=[] 
dll_excludes=['libgdk-win32-1.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll'] 
 
setup( 
 
      options={"py2exe": {"compressed": 2, 
                          "optimize": 2, 
                          "includes": includes, 
                          "excludes": excludes, 
                          "packages": packages, 
                          "dll_excludes": dll_excludes, 
                          "bundle_files": 2, 
                          "dist_dir": "dist", 
                          "xref": False, 
                          "skip_archive": False, 
                          "ascii": False, 
                          "custom_boot_script": '', 
                          } 
               }, 
      windows=['MainWindow.py'],      
      ) 

就我在“dist”文件夹中获得一个可执行应用程序而言,它似乎可以正常工作,当我运行它时,它加载正常,当我插入相同的数据时,它会落在特殊字符(变音符号)处。在 100 个条目中,我成功插入了 60 个,第一次出现重音字符导致可执行文件失败并显示错误消息

(, UnicodeEncodeError('ascii', u'Citro\xebnCX', 5, 6, 'ordinal not in range(128)'), )

碰巧我将 CitroenCX 插入到表格中,'e' 是法语重音字符

我不知道为什么当我从我的 eclipse 环境运行 python/pyqt 应用程序时,我没有收到任何错误,但是一旦我创建了一个可执行文件,我就收到了这个错误。

我应该在我的设置文件中做哪些更改


谢谢。我应用了解决方案

 def setencoding(): 
    encoding = "ascii"  
    if 0: 
        import locale 
        loc = locale.getdefaultlocale() 
        if loc[1]: 
            encoding = loc[1] 
    if 0: #changes comes here, change 0 to 1 
        encoding = "undefined" #the encoding you want 
    if encoding != "ascii": 
        sys.setdefaultencoding(encoding) 

它对我有用。不是原始解决方案,在 SO How to set default encoding in Python (setdefaultencoding() function does not exist)? 上看到它

请您参考如下方法:

区别在于不同环境选择的默认编码。 Unicode 到 stdin 或 stdout 的任何 I/O 都将使用默认编码触发编码或解码。如果该编码是 'ascii',则任何重音字符都将失败。

您可以检查默认值以确保:

import sys 
sys.getdefaultencoding() 
sys.stdin.encoding 
sys.stdout.encoding