Pyinstaller 3如何在--onefile模式下添加数据文件?

3
我有一个名为inventoryScraper.py的Python 3脚本,想将其制作成可分发的1个文件可执行程序。我使用了Pyinstaller 3和Python 3,在过去成功过。我的脚本需要运行一个名为“Store_Codes.csv”的文件,并希望将其包含在可执行文件中。
我已经阅读并尝试了所有之前相关答案,但都没有成功/我搞砸了。当Store_Codes.csv与exe文件在同一文件夹中时,生成的.exe文件可以正常工作,否则就不行。我对Python确实是个新手,但我要把这个交给的人对命令行或任何相关事物都没有经验,因此重要的是它是一个全功能文件。
我已经按照其他帖子所述的所有方式修改了spec文件,但都没有起作用,我确定我理解有误,真的需要帮助。
使用Pyinstaller 3,如何直接地将数据文件包含在onefile exe中?
谢谢!
2个回答

5
  1. Put the Store_Codes.csv in the same folder as the .py file.
  2. On the field data in the .spec file you add datas=[( 'Store_Codes.csv', '.' )],
  3. You should add to your .py file

     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. compile the file.

讨论

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

如果您在spec文件中添加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

0

其实有一个更简单的解决方法,将你的 Store_Codes.csv 重命名为 Store_Codes.py,然后编辑该文件:

csv_codes = """

csv file content...

"""

在你的主脚本中:import Store_Codes,然后使用csv_file_content = Store_Codes.csv_codes
然后在pyinstaller中使用--onefile,它会自动将Store_Codes.py包含在新生成的exe文件中。 P.S. 如果csv文件中的内容是utf-8编码,请不要忘记# -*- coding: utf-8 -*-

我按照你写的做了,但是出现了“ImportError: no module named 'Store_Codes'”的错误。 - Clive
你把 Store_Codes.py 放到与主脚本相同的文件夹里了吗? - Shane
我已经尝试过了,但仍然出现错误。我刚刚测试了主脚本,它的运行是正常的。 - Clive
然后在您的 pyinstaller 命令中添加此参数:--hidden-import=Store_Codes,这将确保在打包时包含该文件。 - Shane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接