python - Pyinstaller 3 使用 --onefile 添加数据文件

标签 python python-3.x executable pyinstaller

我有一个有效的 Python 3 脚本 inventoryScraper.py,我正试图将其制作成一个我可以分发的 1 文件可执行文件。我一直在将 Pyinstaller 3 与 Python 3 一起使用,它在过去一直有效。我有一个我的脚本需要运行的文件“Store_Codes.csv”,我希望它包含在可执行文件中。

我已经阅读并尝试了与此相关的所有先前答案,但没有奏效/我搞砸了。当 Store_Codes.csv 与 exe 位于同一文件夹中时,生成的 .exe 有效,否则无效。我绝对是 Python 的新手,但我将其交给的人没有任何命令行或任何相关经验,因此它是一个一体化文件很重要。

我已经按照我在其他帖子中看到的各种方式修改了 spec 文件,但没有一个奏效,我确信我误解了,我真的可以使用帮助。

使用 Pyinstaller 3 将数据文件包含在一个 onefile exe 中的直接方法是什么?

谢谢!

最佳答案

  1. Store_Codes.csv 放在与 .py 文件相同的文件夹中。
  2. 在 .spec 文件的 data 字段中添加 datas=[( 'Store_Codes.csv', '.' )],
  3. 你应该添加到你的 .py 文件

     if getattr(sys, 'frozen', False):
         # if you are running in a |PyInstaller| bundle
         extDataDir = sys._MEIPASS
         extDataDir  = os.path.join(extDataDir, 'Store_Codes.csv') 
         #you should use extDataDir as the path to your file Store_Codes.csv file
     else:
         # we are running in a normal Python environment
         extDataDir = os.getcwd()
         extDataDir = os.path.join(extDataDir, 'Store_Codes.csv') 
         #you should use extDataDir as the path to your file Store_Codes.csv file
    
  4. 编译文件。

讨论

当您启动 .exe 时,它会在操作系统的适当临时文件夹位置创建一个临时文件夹。该文件夹名为 _MEIxxxxxx,其中 xxxxxx 是一个随机数。运行脚本所需的所有文件都将在那里 sys._MEIPASS 是这个临时文件夹的路径。

当您将 datas=[( 'Store_Codes.csv', '.' )] 添加到规范文件时。它将文件复制到包的主文件夹中。如果你想让它井井有条,你可以使用 datas=[( 'Store_Codes.csv', 'another_folder' )] 创建一个不同的文件夹,然后在你的代码中你会拥有

 if getattr(sys, 'frozen', False):
     # if you are running in a |PyInstaller| bundle
     extDataDir = sys._MEIPASS
     extDataDir  = os.path.join(extDataDir,another_folder, 'Store_Codes.csv') 
     #you should use extDataDir as the path to your file Store_Codes.csv file
 else:
     # we are running in a normal Python environment
     extDataDir = os.getcwd()
     extDataDir = os.path.join(extDataDir,another_folder 'Store_Codes.csv') 
     #you should use extDataDir as the path to your file Store_Codes.csv file

关于python - Pyinstaller 3 使用 --onefile 添加数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864951/

相关文章:

python - 删除numpy数组(矩阵)中的行: Delete previous k rows if value in column j equals k

python - 在 AWS lambda 和 API 网关中部署 Flask sqlalchemy 应用程序

python - 如何在python mysql中防止CREATE查询中的注入(inject)攻击

python - 检测父类中的异常

python - 2-opt 算法解决 Python 中的旅行商问题

c++ - 目标文件和可执行文件各字段大小的区别

c - 过程 : Regarding proc Executable size difference

python - ubuntu9.10 : how to use python's lib-dynload and site-packages directories?

Python 3 异常处理和捕获

linux - 可执行的 while 循环 : no such file or directory