pyinstaller打包pyecharts报错解决

通过 Dockerfile 创建镜像时,发现打包 pyecharts 库后运行报错,遂查询了一下,发现官方并没有支持这个库的打包,只能我自己动手了。

打包好的程序直接运行的话会报 FileNotFoundError:

1
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\x\\AppData\\Local\\Temp\\_MEI6362\\pyecharts\\datasets\\map_filename.json'

查询了一下 Pyinstaller 官方并没有支持

但是找到了解决方法

当前版本(version is 1.6.0),主要需要引入的资源有模板 (pyecharts/render/templates) 和数据集 (pyecharts/datasets)。如果使用 pyinstaller 打包,则需要在打包时指定这些外部资源 (比如在命令行中使用 --add-data 参数),将其和源码(及依赖)一起打包到生成的程序中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|   showmychart.py  # python 源码
|
+---datasets # 资源 datasets
| city_coordinates.json
| countries_regions_db.json
| map_filename.json
| __init__.py
|
\---templates # 资源 templates
components.html
macro
nb_components.html
nb_jupyter_globe.html
nb_jupyter_lab.html
nb_jupyter_lab_tab.html
nb_jupyter_notebook.html
nb_jupyter_notebook_tab.html
nb_nteract.html
simple_chart.html
simple_globe.html
simple_page.html
simple_tab.html

所以解决方案就是通过在命令行中使用 --add-data 命令添加资源文件路径就可以成功打包并运行。

1
pyinstaller -F run.py --distpath . --add-data /usr/local/lib/python3.8/site-packages/pyecharts/datasets:pyecharts/datasets --add-data=/usr/local/lib/python3.8/site-packages/pyecharts/render/templates:pyecharts/render/templates

具体路径大家可以自己修改,我这里由于是用在 docker 中,所以固定了资源文件路径。

参考链接:

https://github.com/pyinstaller/pyinstaller/wiki/Supported-Packages

https://github.com/pyecharts/pyecharts/issues/1419

本文章首发于个人博客 LLLibra146’s blog
本文作者:LLLibra146
版权声明:本博客所有文章除特别声明外,均采用 © BY-NC-ND 许可协议。非商用转载请注明出处!严禁商业转载!
本文链接https://blog.d77.xyz/archives/b256f3c6.html