You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包含Cantera库的Python脚本生成.exe运行异常求助

解决PyInstaller打包Cantera脚本后跨目录运行失效问题

问题分析

从报错日志可明确核心问题:Cantera在转换gri30.cti文件时,调用了系统默认的python命令(指向Python2.7),而非PyInstaller打包的嵌入式Python3.9解释器。系统Python2.7环境未安装Cantera,因此触发ImportError: No module named _cantera。

解决思路与实现

思路1:强制Cantera使用打包后的Python解释器

在脚本开头添加代码,设置Cantera专属环境变量CANTERA_PYTHON,指定其使用当前运行的Python解释器(即打包后的嵌入式Python):

import os
import sys
# 强制Cantera调用当前脚本的Python解释器
os.environ['CANTERA_PYTHON'] = sys.executable

import numpy as np
import cantera as ct
print(np.zeros(2))
S = ct.Solution('gri30.cti')

重新打包命令保持不变:

pyinstaller script.py --collect-all cantera

思路2:预转换CTI文件为CTML,避免动态转换

Cantera加载CTML格式文件时无需启动外部Python进程,可提前完成格式转换:

  1. 在虚拟环境中运行以下代码,将gri30.cti转换为CTML格式的gri30.xml:
import cantera as ct
ct.Solution('gri30.cti').write_xml('gri30.xml')
  1. 修改原脚本,直接加载预转换的CTML文件:
import numpy as np
import cantera as ct
print(np.zeros(2))
# 加载预转换的CTML文件
S = ct.Solution('gri30.xml')
  1. 打包时将CTML文件加入资源列表:
pyinstaller script.py --collect-all cantera --add-data "gri30.xml;."

(Windows系统用;分隔路径,Linux/macOS环境替换为:)

测试方案

  • 思路1测试:将生成的exe复制到无Python2.7或未安装Cantera的机器/目录,运行验证是否能正常加载cti文件。
  • 思路2测试:打包后将exe与gri30.xml放在同一目录(或按打包时的路径配置放置),在无Cantera环境的机器运行,确认无需外部Python即可启动。

内容的提问来源于stack exchange,提问作者pgraums

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:58:36