Search code examples
pythonjsonwindowspyinstallercx-freeze

json.load / simplejson.load fails in packaged Python app (PyInstaller or cx_freeze)


I have a command-line Python app that loads a JSON file specified on the command line:

with open(sys.argv[1]) as f:
    data = json.load(f)

This is all fine and dandy when running the app as-is using the system Python interpreter, but once it's packaged into an EXE via PyInstaller or cx_freeze I get the following error:

Traceback (most recent call last):
  File "<string>", line 92, in <module>
  File "c:\Users\user\Documents\build\main\out00-PYZ.pyz\simplejson"
, line 444, in load
  File "c:\Users\user\Documents\build\main\out00-PYZ.pyz\simplejson"
, line 501, in loads
  File "c:\Users\user\Documents\build\main\out00-PYZ.pyz\simplejson.
decoder", line 370, in decode
  File "c:\Users\user\Documents\build\main\out00-PYZ.pyz\simplejson.
decoder", line 389, in raw_decode
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When using the built-in json module instead, I get another error:

ValueError: No JSON object could be decoded

The JSON file in question is known to be valid and can be loaded without issue from a REPL.

Does anyone have thoughts on what the problem might be?

UPDATE 1: Strangely enough, things work when I replace sys.argv[1] with the hardcoded filename. I've confirmed that sys.argv[1] correctly maps to the filename in the frozen app.

UPDATE 2: I've confirmed that the exception is thrown AFTER the json.load call succeeds - a print statement inserted right after it can be reached.

UPDATE 3: False alarm! This app uses Flask, and it turns out I had debug mode enabled, which caused the autoreloader to attempt to run the main() block again with improper arguments.


Solution

  • False alarm! This app uses Flask, and it turns out I had debug mode enabled, which caused the autoreloader to attempt to run the main() block again with improper arguments.

    If you're using any sort of packager with a FLask app, make sure debug mode is disabled.