[Python][cx-freeze] ImportError: cannot import name 'ExcelFormulaParser'

[Python][cx-freeze] ImportError: cannot import name 'ExcelFormulaParser'

您好,当 运行 cx-freeze 一段 python 代码时,我遇到了一个问题。当我单击由 cx-freeze 生成的可执行文件时,它总是抛出错误消息。任何人都可以帮忙吗? - Python 3.6.1 使用。

我还在另一段 python 代码上 运行 了 cx-freeze 并且运行良好。

错误信息如下:

Last login: Thu Aug 31 14:45:12 on ttys002
EMacBook-Pro:~ E$ /Users/E/PycharmProjects/ImageRename/dist/exportImageName_1 ; exit;
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cx_Freeze/initscripts/__startup__.py", line 14, in run
    module.run()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cx_Freeze/initscripts/Console.py", line 26, in run
    exec(code, m.__dict__)
  File "exportImageName_1.py", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xlwt/__init__.py", line 4, in <module>
    from .Worksheet import Worksheet
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xlwt/Worksheet.py", line 38, in <module>
    from .Row import Row
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xlwt/Row.py", line 8, in <module>
    from . import ExcelFormula
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xlwt/ExcelFormula.py", line 3, in <module>
    from . import ExcelFormulaParser, ExcelFormulaLexer
ImportError: cannot import name 'ExcelFormulaParser'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[进程已完成]

py文件中的源代码:

import xlwt
import os
import FileDirectory_1


def walk_dir(dir):
    rowindex = 1
    for root, dirs, files in os.walk(dir):
        for f in files:
            if "jpg" in f:
                table.write(rowindex,0, root)
                table.write(rowindex,1, f)
                # print(os.path.join(root,f))
                rowindex += 1


dir = FileDirectory_1.DIR;
excelName = "imageRename.xls"

# =======Excel Style============
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = "Arial"
font.bold = True
style.font = font
# ==============================


file = xlwt.Workbook()
table = file.add_sheet("ImageRename", cell_overwrite_ok=True)
table.write(0, 0, "Old File Path", style)
table.write(0, 1, "Old Image Name", style)
table.write(0, 2, "New Image Name", style)

walk_dir(dir)

file.save(os.path.join(dir, excelName))
print(excelName, " has been generated.")

发现问题。我检查了由 cx-freeze 生成的 /lib/xlwt 文件夹中的文件,发现 "ExcelFormulaParser.pyc" 和 "ExcelFormulaLexer.pyc" 文件不知何故丢失了。添加回 "ExcelFormulaParser.py" 和 "ExcelFormulaLexer.py" 文件后,问题已解决。这两个文件是我自己的xlwt文件从site package复制到build文件夹下的

其实根本不需要复制文件。只需将 xlwt 添加为 cx-freeze setup.py 文件中的包依赖项。

例如:

build_exe_options = {"packages": [...your packages.....,  "xlwt"]
                    ...............
                    }

我遇到了同样的问题,这会解决它。