pyuic4生成带有SyntaxError的文件:非ASCII字符'\ xff'

时间:2015-03-12 14:12:17

标签: python qt

注意:这不是通常的“为什么我的编码没有设置?”问题!

我有一个Qt ui文件,我使用以下命令转换为与PyQt4一起使用:

pyuic4 model_importer.ui > model_importer.py

它运行正常,但是当我尝试将其作为模块导入,或者甚至将其作为脚本运行时,它会因以下错误而失败:

File "C:\Users\j\projects\model_importer.py", line 1 SyntaxError: Non-ASCII character '\xff' in file C:\Users\j\model_importer.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

以下代码具有正确的编码,是pyuic4的输出,如果将其粘贴到 new 文件中,则可以正常工作。我的原始文件为here。当文件完全为空时,也会发生此错误,这会导致我认为文件本身存在某种损坏。

有人可以解释这个特殊的错误吗?

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file '.\model_importer.ui'
#
# Created: Thu Mar 12 13:57:45 2015
#      by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_ModelImporterDlg(object):
    def setupUi(self, ModelImporterDlg):
        ModelImporterDlg.setObjectName(_fromUtf8("ModelImporterDlg"))
        ModelImporterDlg.resize(722, 223)
        self.gridLayout_2 = QtGui.QGridLayout(ModelImporterDlg)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.buttonBox = QtGui.QDialogButtonBox(ModelImporterDlg)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.gridLayout_2.addWidget(self.buttonBox, 1, 1, 1, 1)

        self.retranslateUi(ModelImporterDlg)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), ModelImporterDlg.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), ModelImporterDlg.reject)
        QtCore.QMetaObject.connectSlotsByName(ModelImporterDlg)

    def retranslateUi(self, ModelImporterDlg):
        ModelImporterDlg.setWindowTitle(_translate("ModelImporterDlg", "Model Importer", None))
        self.file_tw.setSortingEnabled(True)
        self.file_tw.headerItem().setText(0, _translate("ModelImporterDlg", "Model", None))
        self.file_tw.headerItem().setText(1, _translate("ModelImporterDlg", "Version", None))

import resource_rc

1 个答案:

答案 0 :(得分:1)

这是BOM!显然设置但隐藏在Sublime Text 3中。将"show_encoding": true添加到用户设置,然后将编码更改为UTF-8解决了这个问题。谢谢@ekhumoro

BOM

我的另一种解决方法是直接使用pyuic.py,但似乎无法使用BOM输出:

python C:\osgeo\apps\Python27\Lib\site-packages\PyQt4\uic\pyuic.py -o model_importer.py model_importer.ui