Search code examples
python-3.xcx-freeze

cx_freeze executable crashes with "Program Has Stopped Working" and "No Module Named Codec"


I wrote a Python script that requires a few modules, these being:

PyQt5, plotly, pandas, datetime, xlsxwriter

I am trying to turn these into a .exe using cx_freeze. I have done this once before with a simpler program that relied primarily on PyQt5.

The line:

python setup.py build

completes without errors on the command prompt.

My setup.py file looks like:

  import sys

kwargs = {"name": "x",
          "version": "1.2",
          "author": "x",
          "author_email": "x",
          "description": "x",
          "zip_safe": False
          }

try:
    if sys.argv[1] == "build":
        import os
        from setuptools import find_packages
        from cx_Freeze import setup, Executable

        kwargs["options"] = {
            "build_exe": {
                "packages": find_packages() + ["os", "numpy", "plotly", "xlsxwriter", "sys", "datetime"],
                "includes": ["numpy", "plotly", "pkg_resources", "PyQt5", "xlsxwriter", "sys", "datetime","codecs"],
        }
    }
    kwargs["executables"] = [Executable(r"MyScript.py", 
base="console")]

    setup(**kwargs)
except Exception as e:
    print(e)

The line with [username] has my username in it.

When I run it, the command line reads:

Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
  File "C:\Users\[Username]\AppData\Local\Programs\Python\Python36\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'

UPDATE

After reading more on the internet, it seemed like it might be an install issue. So I've uninstalled and re-installed Python and all the modules I needed after uninstalling Anaconda (just in case it was something to do with the Anaconda distribution). However, I'm still seeing the above error. There is a module named codecs, and the Python script (not the .exe) works fine. I've tried changing my path variable to make sure it points to the correct version of Python (though I've uninstalled all other versions).

Also, I'm running:

OS: Windows 7

Python: Python 3.6.3 64 bit


Solution

  • So it turned out that the issue was cx_freeze. If you use pip to install it, it doesn't install the latest version. Instead, I Googled "cx_freeze download", downloaded the latest .whl for my version of windows, then ran:

    pip install [name of file here].whl
    

    After that there were other issues, but the codec issue was resolved.