简体   繁体   English

Python:如何在pyinstaller中包含数据文件?

[英]Python: how to include data files in pyinstaller?

I'm trying to create an executable of a project with the following structure我正在尝试创建具有以下结构的项目的可执行文件

/projectdir
    project.spec
    /src
        /project
            main.py
            /submodule1
                 f1.py
            /res
                 f2.csv

Inside of f1.py there is a call to read f2.csv with the form open('src/project/res/f2.csv') .f1.py中,有一个读取f2.csv的调用,格式为open('src/project/res/f2.csv') When I package it with build and install it somewhere else, it works without problems.当我 package build并将其安装在其他地方时,它可以正常工作。 However, I'm not able to create a working executable with pyinstaller ( pyinstaller -F project.spec ).但是,我无法使用pyinstaller ( pyinstaller -F project.spec ) 创建可运行的可执行文件。

I've tried adding the file with datas inside of project.spec , as explained in the documentation of pyinstaller :我已经尝试在project.spec中添加带有datas的文件,如pyinstaller文档中所述:

 a = Analysis(['src/project/main.py'],
             pathex=[os.getcwd()+'/venv/lib/python3.8/',
                     os.getcwd()+'/src/'],
             binaries=[],
             datas=[('./src/project/res/f2.csv',
                     '/src/project/res/')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=['tkinter'],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

However, when I execute the generated executable with pyinstaller I get an file not found error:但是,当我使用pyinstaller执行生成的可执行文件时,出现找不到文件错误:

FileNotFoundError: [Errno 2] No such file or directory: 'src/project/res/f2.csv'

What is the correct syntax to access this file?访问此文件的正确语法是什么? Should I change something in the *.spec file or should the call from f1.py be changed?我应该更改*.spec文件中的某些内容还是应该更改来自f1.py的调用?

Many thanks非常感谢

I had the same problem with pyinstaller.我对 pyinstaller 有同样的问题。 I used a workaround hack that worked for me for image and.mo files.我使用了一种适用于图像和 .mo 文件的变通方法。 I created a script that turned the data files into base64. This same script then wrote out another python file containing the base64. This file was then packaged with pyinstaller.我创建了一个将数据文件转换为 base64 的脚本。然后这个相同的脚本写出另一个包含 base64 的 python 文件。然后这个文件用 pyinstaller 打包。 You can then write the file out for use in your software.然后您可以写出该文件以供您的软件使用。 Example below shows both the creator file and the output file.下面的示例显示了创建者文件和 output 文件。 At the end of the main.py file (in the qualcoder folder), I write the data files back out to be used.在 main.py 文件的末尾(在 qualcoder 文件夹中),我将数据文件写回以供使用。

https://github.com/ccbogel/QualCoder/tree/master/qualcoder/locale https://github.com/ccbogel/QualCoder/tree/master/qualcoder/locale

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM