[Solved] Flag + pyinstaller runs error after packaging: SystemError

Cause: the company has a requirement to package flash as exe without displaying the terminal window

Process: try packaging with pyuninstaller first. Without – W parameter, everything is normal when packaging and running;

Problem: after trying to add the – W parameter (hide the terminal window), an error systemerror is found when running

Analysis: tracing the exception stack, it is found that the log output of flask is realized by writing the standard output. When the terminal window is not created, flask will fail to call the write method because it cannot obtain the expected standard output instance (expected to be: _io. Textiowrapper), thus throwing systemerror

Solution: explicitly redirect standard output before flash initialization

import sys
import os

sys.stdout = open(os.devnull, "w")  # Does not retain any standard output

# ------- The following is the original code -------
app = Flask(__name__)  # ...

Finally: Please note that this will invalidate all functions (Methods) that depend on standard output, which may include logs, Therefore, it is best to write to a file when there is little output or define a class or method to encapsulate when there is much output

Similar Posts: