Solve the problem of encoding errors in Pyinstaller packaging as executable files

  • 2021-10-11 19:06:59
  • OfStack

Error message

UnicodeDecodeError: 'utf-8' codec can 't decode byte 0xce in position ***

Solutions

Enter first on the command line


chcp 65001

Then enter the package command.


pyinstaller -F xxx.py

Supplement: Problems and Solutions of Recursive Overbounds and Character Encoding Errors when pyinstaller Packages python Programs

Packaging command: pyinstaller-F xx. py

-F1 must be added, which means to generate independent executable files

Problem 1: Exceeding recursive depth

Because there may be recursive operation in python file, there is no problem in actual execution, but an error will be reported when packaged, and the error message is as follows

RecursionError: maximum recursion depth exceeded

The general meaning is that the recursion depth exceeds the limit allowed by the program, and the maximum is 1000.

Although an error is reported after the execution is completed, an xx. spec file will be generated under the directory at the same level as xx. py file. Open this file. The first line of xx is character coding, and the following two sentences of code are added to the 23rd line of the code.

Then execute the following code (never execute the original package command again)

pyinstaller xx.spec


import sys
sys.setrecursionlimit(6000)

Problem 2: Reporting coding errors when packaging

The error message is as follows:

UnicodeDecodeError: 'utf-8' codec can 't decode byte 0xce in position 121: invalid start byte

It may be a bit covered, clearly the code statement in the code why also report errors, don't panic, in the dos window (windows+R, enter cmd) before entering the packaging command, enter the following command first, and execute carriage return


chcp 65001

Then enter the package command. If an encoding error occurs after modifying the spec file because of a recursive error at first, the package command is still executed


pyinstaller xx.spec

Problem 3: File read path in the original code, report error after packing, and can't find the path

The original code is as follows:

Using abspath to get the path is not feasible, and there will be no errors when the program runs. When packaging, replace it with the following code to get the path


import os
path1 = os.path.dirname(os.path.abspath(__file__))
path2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Replace with


import os
import sys
path1 = os.path.dirname(os.path.realpath(sys.executable))
path2 = os.path.dirname(os.path.dirname(os.path.realpath(sys.executable)))

Question 4: No problem when packing, exe flashback is generated, and no error message can be seen.

Solution: Open an dos window, drag the exe file into the dos window, and then enter to execute.


Related articles: