'Import pyqt file: ValueError: source code string cannot contain null bytes

I've generated (pyuic5) ui_mainwindow.py file from .ui file made in Qt Designer:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        ....

I try to import class Ui_MainWindow in my main.py from ui_mainwindow.py:

from ui_mainwindow import Ui_MainWindow

and I'm getting this error:

ValueError: source code string cannot contain null bytes

What have I done wrong?



Solution 1:[1]

The error is due to different ascii coding of the source Load the ui_mainwindow.py in an editor like notepad++ change the encoding to UTF-8 and save the file.

Solution 2:[2]

Probably you used 'pyside2-uic' in terminal to generate ui_mainwindow.py code, command which created a file with different encoding type than UTF-8.

I suggest to copy that code, create a new .py file and paste your code in that file, that should work.

And if you use Qt Designer to create your interface, you have option to get python code from Form -> View Python Code. This way you avoid using the terminal to generate the code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rindert
Solution 2